id
int64
0
755k
file_name
stringlengths
3
109
file_path
stringlengths
13
185
content
stringlengths
31
9.38M
size
int64
31
9.38M
language
stringclasses
1 value
extension
stringclasses
11 values
total_lines
int64
1
340k
avg_line_length
float64
2.18
149k
max_line_length
int64
7
2.22M
alphanum_fraction
float64
0
1
repo_name
stringlengths
6
65
repo_stars
int64
100
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
9 values
repo_extraction_date
stringclasses
92 values
exact_duplicates_redpajama
bool
2 classes
near_duplicates_redpajama
bool
2 classes
exact_duplicates_githubcode
bool
2 classes
exact_duplicates_stackv2
bool
1 class
exact_duplicates_stackv1
bool
2 classes
near_duplicates_githubcode
bool
2 classes
near_duplicates_stackv1
bool
2 classes
near_duplicates_stackv2
bool
1 class
752,729
PscCoder.hpp
Orvid_Champollion/Decompiler/PscCoder.hpp
#pragma once #include "Coder.hpp" namespace Decompiler { static const char* WARNING_COMMENT_PREFIX = ";***"; /** * @brief Write a PEX file as a PSC file. */ class PscCoder : public Coder { public: PscCoder(OutputWriter *writer, bool commentAsm, bool writeHeader, bool traceDecompilation, bool dumpTree, bool writeDebugFuncs, bool printDebugLineNo, std::string traceDir); PscCoder(OutputWriter* writer); ~PscCoder(); virtual void code(const Pex::Binary& pex); PscCoder& outputDecompilationTrace(bool traceDecompilation); PscCoder& outputDumpTree(bool dumpTree); PscCoder& outputAsmComment(bool commentAsm); PscCoder& outputWriteHeader(bool writeHeader); static std::string mapType(std::string type); protected: void writeHeader(const Pex::Binary& pex); void writeObject(const Pex::Object& object, const Pex::Binary& pex); void writeStructs(const Pex::Object& object, const Pex::Binary& pex); void writeStructMember(const Pex::StructInfo::Member& member, const Pex::Binary& pex); void writeProperties(const Pex::Object& object, const Pex::Binary& pex); void writeProperty(int i, const Pex::Property& prop, const Pex::Object &object, const Pex::Binary& pex); void writeVariables(const Pex::Object& object, const Pex::Binary& pex); void writeGuards(const Pex::Object& object, const Pex::Binary& pex); void writeStates(const Pex::Object& object, const Pex::Binary& pex); void writeFunctions(int i, const Pex::State& state, const Pex::Object &object, const Pex::Binary& pex); void writeFunction(int i, const Pex::Function &function, const Pex::Object &object, const Pex::Binary &pex, const Pex::DebugInfo::FunctionInfo *functionInfo, const std::string &name = ""); void writeUserFlag(std::ostream &stream, const Pex::UserFlagged& flagged, const Pex::Binary& pex); void writeDocString(int i, const Pex::DocumentedItem& item); protected: bool m_CommentAsm; bool m_WriteHeader; bool m_TraceDecompilation; bool m_DumpTree; bool m_WriteDebugFuncs; bool m_PrintDebugLineNo; std::string m_OutputDir; bool isNativeObject(const Pex::Object &object, const Pex::Binary::ScriptType &scriptType) const; bool isCompilerGeneratedFunc(const std::string &name, const Pex::Object &object, Pex::Binary::ScriptType scriptType) const; }; }
2,450
C++
.h
50
43.26
109
0.715781
Orvid/Champollion
106
20
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,734
PscDecompiler.hpp
Orvid_Champollion/Decompiler/PscDecompiler.hpp
#pragma once #include <vector> #include <string> #include <fstream> #include <map> #include "Pex/Object.hpp" #include "PscCodeBlock.hpp" #include "Node/Base.hpp" #include "Pex/DebugInfo.hpp" namespace Decompiler { /** * @brief Decompiler class. * * This class contains the core process of the decompilation sequence. * The result is stored as string in the vector part of the class. */ class PscDecompiler : public std::vector<std::string> { public: typedef std::map<size_t, std::vector<uint16_t>> DebugLineMap; PscDecompiler(const Pex::Function &function, const Pex::Object &object, const Pex::DebugInfo::FunctionInfo *debugInfo, bool commentAsm, bool traceDecompilation, bool dumpTree, std::string outputDir); ~PscDecompiler(); void decodeToAsm(std::uint8_t level, size_t begin, size_t end); bool isDebugFunction(); const Pex::DebugInfo::FunctionInfo & getDebugInfo(); void addLineMapping(size_t decompiledLine, std::vector<uint16_t> &originalLines); DebugLineMap &getLineMap(); protected: void findVarTypes(); const Pex::StringTable::Index& typeOfVar(const Pex::StringTable::Index& var) const; void createFlowBlocks(); void createNodesForBlocks(size_t bloc); size_t findBlockForInstruction(size_t ip); void rebuildExpressionsInBlocks(); void rebuildExpression(Node::BasePtr scope); void rebuildBooleanOperators(size_t startBlock, size_t endBlock); Node::BasePtr rebuildControlFlow(size_t startBlock, size_t endBlock); Node::BasePtr findScopeForVariable(const Pex::StringTable::Index& var, Node::BasePtr enclosingScope); void declareVariables(Node::BasePtr program); void cleanUpTree(Node::BasePtr program); void generateCode(Node::BasePtr program); Pex::StringTable::Index toIdentifier(const Pex::Value& value) const; Node::BasePtr fromValue(size_t ip, const Pex::Value& value) const; Node::BasePtr checkAssign(Node::BasePtr expression) const; void dumpBlock(size_t startBlock, size_t endBlock); protected: typedef std::map<size_t, PscCodeBlock*> CodeBlocs; CodeBlocs m_CodeBlocs; typedef std::map<std::uint16_t, Pex::StringTable::Index> VarToProperties; VarToProperties m_VarToProperties; typedef std::map<std::uint16_t, Pex::StringTable::Index> VarTypes; VarTypes m_VarTypes; Pex::StringTable::Index m_NoneVar; const Pex::Function& m_Function; const Pex::Object& m_Object; bool m_ReturnNone; bool m_CommentAsm; bool m_TraceDecompilation; bool m_DumpTree; const Pex::DebugInfo::FunctionInfo m_DebugInfo; std::string m_OutputDir; std::ofstream m_Log; Pex::StringTable m_TempTable; // Map of decompiled lines to the range of (potentially multiple) original lines that were in the debug info DebugLineMap m_LineMap; void rebuildLocks(Node::BasePtr &program); void RemoveUnlocksFromBody(Node::BasePtr &body, const Node::BasePtr &matchingLock); void LiftLockBody(std::shared_ptr<Node::Base> &guard); }; }
3,069
C++
.h
73
37.438356
112
0.739057
Orvid/Champollion
106
20
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,736
EventNames.hpp
Orvid_Champollion/Decompiler/EventNames.hpp
#pragma once #include <vector> #include <string> namespace Decompiler{ namespace Skyrim { static const std::vector<std::string> NativeClasses ={}; static const std::vector<std::string> EventNames = { "OnAnimationEvent", // ActiveMagicEffect "OnAnimationEventUnregistered", // ActiveMagicEffect "OnEffectFinish", // ActiveMagicEffect "OnEffectStart", // ActiveMagicEffect "OnGainLOS", // ActiveMagicEffect "OnLostLOS", // ActiveMagicEffect "OnUpdate", // ActiveMagicEffect "OnCombatStateChanged", // Actor "OnDeath", // Actor "OnDying", // Actor "OnEnterBleedout", // Actor "OnGetUp", // Actor "OnLocationChange", // Actor "OnLycanthropyStateChanged", // Actor "OnObjectEquipped", // Actor "OnObjectUnequipped", // Actor "OnPackageChange", // Actor "OnPackageEnd", // Actor "OnPackageStart", // Actor "OnPlayerBowShot", // Actor "OnPlayerFastTravelEnd", // Actor "OnPlayerLoadGame", // Actor "OnRaceSwitchComplete", // Actor "OnSit", // Actor "OnVampireFeed", // Actor "OnVampirismStateChanged", // Actor "OnAnimationEvent", // Alias "OnAnimationEventUnregistered", // Alias "OnGainLOS", // Alias "OnLostLOS", // Alias "OnReset", // Alias "OnUpdate", // Alias "OnAnimationEvent", // Form "OnAnimationEventUnregistered", // Form "OnGainLOS", // Form "OnLostLOS", // Form "OnSleepStart", // Form "OnSleepStop", // Form "OnTrackedStatsEvent", // Form "OnUpdate", // Form "OnUpdateGameTime", // Form "OnActivate", // ObjectReference "OnAttachedToCell", // ObjectReference "OnCellAttach", // ObjectReference "OnCellDetach", // ObjectReference "OnCellLoad", // ObjectReference "OnClose", // ObjectReference "OnContainerChanged", // ObjectReference "OnDestructionStageChanged", // ObjectReference "OnDetachedFromCell", // ObjectReference "OnEquipped", // ObjectReference "OnGrab", // ObjectReference "OnHit", // ObjectReference "OnItemAdded", // ObjectReference "OnItemRemoved", // ObjectReference "OnLoad", // ObjectReference "OnLockStateChanged", // ObjectReference "OnMagicEffectApply", // ObjectReference "OnOpen", // ObjectReference "OnRead", // ObjectReference "OnRelease", // ObjectReference "OnReset", // ObjectReference "OnSell", // ObjectReference "OnSpellCast", // ObjectReference "OnTranslationAlmostComplete", // ObjectReference "OnTranslationComplete", // ObjectReference "OnTranslationFailed", // ObjectReference "OnTrapHit", // ObjectReference "OnTrapHitStart", // ObjectReference "OnTrapHitStop", // ObjectReference "OnTrigger", // ObjectReference "OnTriggerEnter", // ObjectReference "OnTriggerLeave", // ObjectReference "OnUnequipped", // ObjectReference "OnUnload", // ObjectReference "OnWardHit", // ObjectReference "OnReset", // Quest "OnStoryActivateActor", // Quest "OnStoryAddToPlayer", // Quest "OnStoryArrest", // Quest "OnStoryAssaultActor", // Quest "OnStoryBribeNPC", // Quest "OnStoryCastMagic", // Quest "OnStoryChangeLocation", // Quest "OnStoryCraftItem", // Quest "OnStoryCrimeGold", // Quest "OnStoryCure", // Quest "OnStoryDialogue", // Quest "OnStoryDiscoverDeadBody", // Quest "OnStoryEscapeJail", // Quest "OnStoryFlatterNPC", // Quest "OnStoryHello", // Quest "OnStoryIncreaseLevel", // Quest "OnStoryIncreaseSkill", // Quest "OnStoryInfection", // Quest "OnStoryIntimidateNPC", // Quest "OnStoryJail", // Quest "OnStoryKillActor", // Quest "OnStoryNewVoicePower", // Quest "OnStoryPayFine", // Quest "OnStoryPickLock", // Quest "OnStoryPlayerGetsFavor", // Quest "OnStoryRelationshipChange", // Quest "OnStoryRemoveFromPlayer", // Quest "OnStoryScript", // Quest "OnStoryServedTime", // Quest "OnStoryTrespass", // Quest "OnBeginState", "OnEndState", "OnInit" }; static const std::vector<std::string> EventNamesLowerCase = { "onanimationevent", // ActiveMagicEffect "onanimationeventunregistered", // ActiveMagicEffect "oneffectfinish", // ActiveMagicEffect "oneffectstart", // ActiveMagicEffect "ongainlos", // ActiveMagicEffect "onlostlos", // ActiveMagicEffect "onupdate", // ActiveMagicEffect "oncombatstatechanged", // Actor "ondeath", // Actor "ondying", // Actor "onenterbleedout", // Actor "ongetup", // Actor "onlocationchange", // Actor "onlycanthropystatechanged", // Actor "onobjectequipped", // Actor "onobjectunequipped", // Actor "onpackagechange", // Actor "onpackageend", // Actor "onpackagestart", // Actor "onplayerbowshot", // Actor "onplayerfasttravelend", // Actor "onplayerloadgame", // Actor "onraceswitchcomplete", // Actor "onsit", // Actor "onvampirefeed", // Actor "onvampirismstatechanged", // Actor "onanimationevent", // Alias "onanimationeventunregistered", // Alias "ongainlos", // Alias "onlostlos", // Alias "onreset", // Alias "onupdate", // Alias "onanimationevent", // Form "onanimationeventunregistered", // Form "ongainlos", // Form "onlostlos", // Form "onsleepstart", // Form "onsleepstop", // Form "ontrackedstatsevent", // Form "onupdate", // Form "onupdategametime", // Form "onactivate", // ObjectReference "onattachedtocell", // ObjectReference "oncellattach", // ObjectReference "oncelldetach", // ObjectReference "oncellload", // ObjectReference "onclose", // ObjectReference "oncontainerchanged", // ObjectReference "ondestructionstagechanged", // ObjectReference "ondetachedfromcell", // ObjectReference "onequipped", // ObjectReference "ongrab", // ObjectReference "onhit", // ObjectReference "onitemadded", // ObjectReference "onitemremoved", // ObjectReference "onload", // ObjectReference "onlockstatechanged", // ObjectReference "onmagiceffectapply", // ObjectReference "onopen", // ObjectReference "onread", // ObjectReference "onrelease", // ObjectReference "onreset", // ObjectReference "onsell", // ObjectReference "onspellcast", // ObjectReference "ontranslationalmostcomplete", // ObjectReference "ontranslationcomplete", // ObjectReference "ontranslationfailed", // ObjectReference "ontraphit", // ObjectReference "ontraphitstart", // ObjectReference "ontraphitstop", // ObjectReference "ontrigger", // ObjectReference "ontriggerenter", // ObjectReference "ontriggerleave", // ObjectReference "onunequipped", // ObjectReference "onunload", // ObjectReference "onwardhit", // ObjectReference "onreset", // Quest "onstoryactivateactor", // Quest "onstoryaddtoplayer", // Quest "onstoryarrest", // Quest "onstoryassaultactor", // Quest "onstorybribenpc", // Quest "onstorycastmagic", // Quest "onstorychangelocation", // Quest "onstorycraftitem", // Quest "onstorycrimegold", // Quest "onstorycure", // Quest "onstorydialogue", // Quest "onstorydiscoverdeadbody", // Quest "onstoryescapejail", // Quest "onstoryflatternpc", // Quest "onstoryhello", // Quest "onstoryincreaselevel", // Quest "onstoryincreaseskill", // Quest "onstoryinfection", // Quest "onstoryintimidatenpc", // Quest "onstoryjail", // Quest "onstorykillactor", // Quest "onstorynewvoicepower", // Quest "onstorypayfine", // Quest "onstorypicklock", // Quest "onstoryplayergetsfavor", // Quest "onstoryrelationshipchange", // Quest "onstoryremovefromplayer", // Quest "onstoryscript", // Quest "onstoryservedtime", // Quest "onstorytrespass", // Quest "onbeginstate", "onendstate", "oninit" }; } namespace Fallout4{ static const std::vector<std::string> NativeClasses ={ "Action", "Activator", "ActiveMagicEffect", "Actor", "ActorBase", "ActorValue", "Alias", "Ammo", "Armor", "AssociationType", "Book", "CameraShot", "Cell", "Class", "CombatStyle", "Component", "ConstructibleObject", "Container", "Debug", "Door", "EffectShader", "Enchantment", "EncounterZone", "Explosion", "Faction", "Flora", "Form", "FormList", "Furniture", "Game", "GlobalVariable", "Hazard", "HeadPart", "Holotape", "Idle", "IdleMarker", "ImageSpaceModifier", "ImpactDataSet", "Ingredient", "InputEnableLayer", "InstanceNamingRules", "Key", "Keyword", "LeveledActor", "LeveledItem", "LeveledSpell", "Light", "Location", "LocationAlias", "LocationRefType", "MagicEffect", "Math", "Message", "MiscObject", "MovableStatic", "MusicType", "ObjectMod", "ObjectReference", "Outfit", "OutputModel", "Package", "Perk", "Potion", "Projectile", "Quest", "Race", "RefCollectionAlias", "ReferenceAlias", "Scene", "ScriptObject", "Scroll", "ShaderParticleGeometry", "Shout", "SoulGem", "Sound", "SoundCategory", "SoundCategorySnapshot", "Spell", "Static", "TalkingActivator", "Terminal", "TextureSet", "Topic", "TopicInfo", "Utility", "VisualEffect", "VoiceType", "Weapon", "Weather", "WordOfPower", "WorldSpace", }; static const std::vector<std::string> EventNames = { "OnEffectFinish", // ActiveMagicEffect "OnEffectStart", // ActiveMagicEffect "OnCombatStateChanged", // Actor "OnCommandModeCompleteCommand", // Actor "OnCommandModeEnter", // Actor "OnCommandModeExit", // Actor "OnCommandModeGiveCommand", // Actor "OnCompanionDismiss", // Actor "OnConsciousnessStateChanged", // Actor "OnCripple", // Actor "OnDeath", // Actor "OnDeferredKill", // Actor "OnDifficultyChanged", // Actor "OnDying", // Actor "OnEnterBleedout", // Actor "OnEnterSneaking", // Actor "OnEscortWaitStart", // Actor "OnEscortWaitStop", // Actor "OnGetUp", // Actor "OnItemEquipped", // Actor "OnItemUnequipped", // Actor "OnKill", // Actor "OnLocationChange", // Actor "OnPackageChange", // Actor "OnPackageEnd", // Actor "OnPackageStart", // Actor "OnPartialCripple", // Actor "OnPickpocketFailed", // Actor "OnPlayerCreateRobot", // Actor "OnPlayerEnterVertibird", // Actor "OnPlayerFallLongDistance", // Actor "OnPlayerFireWeapon", // Actor "OnPlayerHealTeammate", // Actor "OnPlayerLoadGame", // Actor "OnPlayerModArmorWeapon", // Actor "OnPlayerModRobot", // Actor "OnPlayerSwimming", // Actor "OnPlayerUseWorkBench", // Actor "OnRaceSwitchComplete", // Actor "OnSit", // Actor "OnSpeechChallengeAvailable", // Actor "OnAliasInit", // Alias "OnAliasReset", // Alias "OnAliasShutdown", // Alias "OnLocationCleared", // Location "OnLocationLoaded", // Location "OnActivate", // ObjectReference "OnCellAttach", // ObjectReference "OnCellDetach", // ObjectReference "OnCellLoad", // ObjectReference "OnClose", // ObjectReference "OnContainerChanged", // ObjectReference "OnDestructionStageChanged", // ObjectReference "OnEquipped", // ObjectReference "OnExitFurniture", // ObjectReference "OnGrab", // ObjectReference "OnHolotapeChatter", // ObjectReference "OnHolotapePlay", // ObjectReference "OnItemAdded", // ObjectReference "OnItemRemoved", // ObjectReference "OnLoad", // ObjectReference "OnLockStateChanged", // ObjectReference "OnOpen", // ObjectReference "OnPipboyRadioDetection", // ObjectReference "OnPlayerDialogueTarget", // ObjectReference "OnPowerOff", // ObjectReference "OnPowerOn", // ObjectReference "OnRead", // ObjectReference "OnRelease", // ObjectReference "OnReset", // ObjectReference "OnSell", // ObjectReference "OnSpellCast", // ObjectReference "OnTranslationAlmostComplete", // ObjectReference "OnTranslationComplete", // ObjectReference "OnTranslationFailed", // ObjectReference "OnTrapHitStart", // ObjectReference "OnTrapHitStop", // ObjectReference "OnTriggerEnter", // ObjectReference "OnTriggerLeave", // ObjectReference "OnUnequipped", // ObjectReference "OnUnload", // ObjectReference "OnWorkshopMode", // ObjectReference "OnWorkshopNPCTransfer", // ObjectReference "OnWorkshopObjectDestroyed", // ObjectReference "OnWorkshopObjectGrabbed", // ObjectReference "OnWorkshopObjectMoved", // ObjectReference "OnWorkshopObjectPlaced", // ObjectReference "OnWorkshopObjectRepaired", // ObjectReference "OnChange", // Package "OnEnd", // Package "OnStart", // Package "OnEntryRun", // Perk "OnQuestInit", // Quest "OnQuestShutdown", // Quest "OnStageSet", // Quest "OnStoryIncreaseLevel", // Quest "OnAction", // Scene "OnBegin", // Scene "OnEnd", // Scene "OnPhaseBegin", // Scene "OnPhaseEnd", // Scene "OnAnimationEvent", // ScriptObject "OnAnimationEventUnregistered", // ScriptObject "OnBeginState", // ScriptObject "OnControlDown", // ScriptObject "OnControlUp", // ScriptObject "OnDistanceGreaterThan", // ScriptObject "OnDistanceLessThan", // ScriptObject "OnEndState", // ScriptObject "OnFurnitureEvent", // ScriptObject "OnGainLOS", // ScriptObject "OnHit", // ScriptObject "OnInit", // ScriptObject "OnKeyDown", // ScriptObject "OnKeyUp", // ScriptObject "OnLooksMenuEvent", // ScriptObject "OnLostLOS", // ScriptObject "OnMagicEffectApply", // ScriptObject "OnMenuOpenCloseEvent", // ScriptObject "OnPlayerCameraState", // ScriptObject "OnPlayerSleepStart", // ScriptObject "OnPlayerSleepStop", // ScriptObject "OnPlayerTeleport", // ScriptObject "OnPlayerWaitStart", // ScriptObject "OnPlayerWaitStop", // ScriptObject "OnRadiationDamage", // ScriptObject "OnTimer", // ScriptObject "OnTimerGameTime", // ScriptObject "OnTrackedStatsEvent", // ScriptObject "OnTutorialEvent", // ScriptObject "OnMenuItemRun", // Terminal "OnBegin", // TopicInfo "OnEnd", // TopicInfo }; static const std::vector<std::string> EventNamesLowerCase = { "oneffectfinish", // ActiveMagicEffect "oneffectstart", // ActiveMagicEffect "oncombatstatechanged", // Actor "oncommandmodecompletecommand", // Actor "oncommandmodeenter", // Actor "oncommandmodeexit", // Actor "oncommandmodegivecommand", // Actor "oncompaniondismiss", // Actor "onconsciousnessstatechanged", // Actor "oncripple", // Actor "ondeath", // Actor "ondeferredkill", // Actor "ondifficultychanged", // Actor "ondying", // Actor "onenterbleedout", // Actor "onentersneaking", // Actor "onescortwaitstart", // Actor "onescortwaitstop", // Actor "ongetup", // Actor "onitemequipped", // Actor "onitemunequipped", // Actor "onkill", // Actor "onlocationchange", // Actor "onpackagechange", // Actor "onpackageend", // Actor "onpackagestart", // Actor "onpartialcripple", // Actor "onpickpocketfailed", // Actor "onplayercreaterobot", // Actor "onplayerentervertibird", // Actor "onplayerfalllongdistance", // Actor "onplayerfireweapon", // Actor "onplayerhealteammate", // Actor "onplayerloadgame", // Actor "onplayermodarmorweapon", // Actor "onplayermodrobot", // Actor "onplayerswimming", // Actor "onplayeruseworkbench", // Actor "onraceswitchcomplete", // Actor "onsit", // Actor "onspeechchallengeavailable", // Actor "onaliasinit", // Alias "onaliasreset", // Alias "onaliasshutdown", // Alias "onlocationcleared", // Location "onlocationloaded", // Location "onactivate", // ObjectReference "oncellattach", // ObjectReference "oncelldetach", // ObjectReference "oncellload", // ObjectReference "onclose", // ObjectReference "oncontainerchanged", // ObjectReference "ondestructionstagechanged", // ObjectReference "onequipped", // ObjectReference "onexitfurniture", // ObjectReference "ongrab", // ObjectReference "onholotapechatter", // ObjectReference "onholotapeplay", // ObjectReference "onitemadded", // ObjectReference "onitemremoved", // ObjectReference "onload", // ObjectReference "onlockstatechanged", // ObjectReference "onopen", // ObjectReference "onpipboyradiodetection", // ObjectReference "onplayerdialoguetarget", // ObjectReference "onpoweroff", // ObjectReference "onpoweron", // ObjectReference "onread", // ObjectReference "onrelease", // ObjectReference "onreset", // ObjectReference "onsell", // ObjectReference "onspellcast", // ObjectReference "ontranslationalmostcomplete", // ObjectReference "ontranslationcomplete", // ObjectReference "ontranslationfailed", // ObjectReference "ontraphitstart", // ObjectReference "ontraphitstop", // ObjectReference "ontriggerenter", // ObjectReference "ontriggerleave", // ObjectReference "onunequipped", // ObjectReference "onunload", // ObjectReference "onworkshopmode", // ObjectReference "onworkshopnpctransfer", // ObjectReference "onworkshopobjectdestroyed", // ObjectReference "onworkshopobjectgrabbed", // ObjectReference "onworkshopobjectmoved", // ObjectReference "onworkshopobjectplaced", // ObjectReference "onworkshopobjectrepaired", // ObjectReference "onchange", // Package "onend", // Package "onstart", // Package "onentryrun", // Perk "onquestinit", // Quest "onquestshutdown", // Quest "onstageset", // Quest "onstoryincreaselevel", // Quest "onaction", // Scene "onbegin", // Scene "onend", // Scene "onphasebegin", // Scene "onphaseend", // Scene "onanimationevent", // ScriptObject "onanimationeventunregistered", // ScriptObject "onbeginstate", // ScriptObject "oncontroldown", // ScriptObject "oncontrolup", // ScriptObject "ondistancegreaterthan", // ScriptObject "ondistancelessthan", // ScriptObject "onendstate", // ScriptObject "onfurnitureevent", // ScriptObject "ongainlos", // ScriptObject "onhit", // ScriptObject "oninit", // ScriptObject "onkeydown", // ScriptObject "onkeyup", // ScriptObject "onlooksmenuevent", // ScriptObject "onlostlos", // ScriptObject "onmagiceffectapply", // ScriptObject "onmenuopencloseevent", // ScriptObject "onplayercamerastate", // ScriptObject "onplayersleepstart", // ScriptObject "onplayersleepstop", // ScriptObject "onplayerteleport", // ScriptObject "onplayerwaitstart", // ScriptObject "onplayerwaitstop", // ScriptObject "onradiationdamage", // ScriptObject "ontimer", // ScriptObject "ontimergametime", // ScriptObject "ontrackedstatsevent", // ScriptObject "ontutorialevent", // ScriptObject "onmenuitemrun", // Terminal "onbegin", // TopicInfo "onend", // TopicInfo }; } namespace Starfield { static const std::vector<std::string> NativeClasses = { //Forms "Action", "Activator", "ActiveMagicEffect", "Actor", "ActorBase", "ActorValue", "AffinityEvent", "Alias", "Ammo", "Armor", "AssociationType", "Book", "CameraShot", "Cell", "Challenge", "Class", "CombatStyle", "ConditionForm", "ConstructibleObject", "Container", "Curve", "Debug", "Door", "EffectShader", "Enchantment", "Explosion", "Faction", "Flora", "Form", "FormList", "Furniture", "GlobalVariable", "Hazard", "HeadPart", "Idle", "IdleMarker", "ImageSpaceModifier", "ImpactDataSet", "Ingredient", "InputEnableLayer", "InstanceNamingRules", "Key", "Keyword", "LegendaryItem", "LeveledActor", "LeveledItem", "LeveledSpaceshipBase", "LeveledSpell", "Light", "Location", "LocationAlias", "LocationRefType", "MagicEffect", "Message", "MiscObject", "MovableStatic", "MusicType", "Note", "ObjectMod", "ObjectReference", "Outfit", "Package", "PackIn", "Perk", "Planet", "Potion", "Projectile", "Quest", "Race", "RefCollectionAlias", "ReferenceAlias", "ResearchProject", "Resource", "Scene", "Scroll", "ShaderParticleGeometry", "Shout", "SoulGem", "SpaceshipBase", "SpaceshipReference", "Spell", "Static", "TalkingActivator", "Terminal", "TerminalMenu", "TextureSet", "Topic", "TopicInfo", "VisualEffect", "VoiceType", "Weapon", "Weather", "WordOfPower", "WorldSpace", "WwiseEvent", // Non Form Natives "SpeechChallengeObject", "Game", "Math", "ScriptObject", "Utility", }; static const std::vector<std::string> EventNames = { "OnAction", "OnActivate", "OnActorActivatedRef", "OnActorValueChanged", "OnActorValueGreaterThan", "OnActorValueLessThan", "OnAffinityEvent", "OnAffinityEventSent", "OnAliasChanged", "OnAliasInit", "OnAliasReset", "OnAliasShutdown", "OnAliasStarted", "OnAnimationEvent", "OnAnimationEventUnregistered", "OnBegin", "OnBeginState", "OnBuilderMenuSelect", "OnCellAttach", "OnCellDetach", "OnCellLoad", "OnChallengeCompleted", "OnChange", "OnClose", "OnCombatListAdded", "OnCombatListRemoved", "OnCombatStateChanged", "OnCommandModeCompleteCommand", "OnCommandModeEnter", "OnCommandModeExit", "OnCommandModeGiveCommand", "OnCompanionDismiss", "OnConsciousnessStateChanged", "OnContainerChanged", "OnCrewAssigned", "OnCrewDismissed", "OnCripple", "OnDeath", "OnDeferredKill", "OnDestroyed", "OnDestructionStageChanged", "OnDifficultyChanged", "OnDistanceGreaterThan", "OnDistanceLessThan", "OnDying", "OnEffectFinish", "OnEffectStart", "OnEnd", "OnEndState", "OnEnterBleedout", "OnEnterFurniture", "OnEnterOutpostBeaconMode", "OnEnterShipInterior", "OnEnterSneaking", "OnEntryRun", "OnEquipped", "OnEscortWaitStart", "OnEscortWaitStop", "OnExitFurniture", "OnExitShipInterior", "OnGainLOS", "OnGetUp", "OnGrab", "OnHit", "OnHomeShipSet", "OnInit", "OnItemAdded", "OnItemEquipped", "OnItemRemoved", "OnItemUnequipped", "OnKill", "OnLoad", "OnLocationChange", "OnLocationExplored", "OnLocationLoaded", "OnLockStateChanged", "OnLostLOS", "OnMagicEffectApply", "OnMapMarkerDiscovered", "OnMenuOpenCloseEvent", "OnMissionAccepted", "OnObjectDestroyed", "OnObjectRepaired", "OnOpen", "OnOutpostItemPowerOff", "OnOutpostItemPowerOn", "OnOutpostPlaced", "OnPackageChange", "OnPackageEnd", "OnPackageStart", "OnPartialCripple", "OnPhaseBegin", "OnPhaseEnd", "OnPickLock", "OnPickpocketFailed", "OnPipboyRadioDetection", "OnPlanetSiteSelectEvent", "OnPlayerArrested", "OnPlayerAssaultActor", "OnPlayerBuyShip", "OnPlayerCompleteResearch", "OnPlayerCraftItem", "OnPlayerCreateRobot", "OnPlayerCrimeGold", "OnPlayerDialogueTarget", "OnPlayerEnterVertibird", "OnPlayerFailedPlotRoute", "OnPlayerFallLongDistance", "OnPlayerFireWeapon", "OnPlayerFollowerWarp", "OnPlayerHealTeammate", "OnPlayerItemAdded", "OnPlayerJail", "OnPlayerLoadGame", "OnPlayerLoiteringBegin", "OnPlayerLoiteringEnd", "OnPlayerModArmorWeapon", "OnPlayerModifiedShip", "OnPlayerModRobot", "OnPlayerMurderActor", "OnPlayerPayFine", "OnPlayerPlanetSurveyComplete", "OnPlayerScannedObject", "OnPlayerSellShip", "OnPlayerSleepStart", "OnPlayerSleepStop", "OnPlayerSwimming", "OnPlayerTeleport", "OnPlayerTrespass", "OnPlayerUseWorkBench", "OnPlayerWaitStart", "OnPlayerWaitStop", "OnPowerOff", "OnPowerOn", "OnQuestInit", "OnQuestRejected", "OnQuestShutdown", "OnQuestStarted", "OnQuestTimerEnd", "OnQuestTimerMod", "OnQuestTimerPause", "OnQuestTimerResume", "OnQuestTimerStart", "OnQuickContainerOpened", "OnRaceSwitchComplete", "OnRadiationDamage", "OnRead", "OnRecoverFromBleedout", "OnRelease", "OnReset", "OnScanned", "OnSell", "OnShipBought", "OnShipDock", "OnShipFarTravel", "OnShipGravJump", "OnShipLanding", "OnShipRampDown", "OnShipRefueled", "OnShipScan", "OnShipSold", "OnShipSystemDamaged", "OnShipSystemPowerChange", "OnShipSystemRepaired", "OnShipTakeOff", "OnShipUndock", "OnSit", "OnSpeechChallengeAvailable", "OnSpeechChallengeCompletion", "OnSpellCast", "OnStageSet", "OnStarmapTargetSelectEvent", "OnStart", "OnStoryActivateActor", "OnStoryActorAttach", "OnStoryAddToPlayer", "OnStoryArrest", "OnStoryAssaultActor", "OnStoryAttractionObject", "OnStoryBribeNPC", "OnStoryCastMagic", "OnStoryChangeLocation", "OnStoryCraftItem", "OnStoryCrimeGold", "OnStoryCure", "OnStoryDialogue", "OnStoryDiscoverDeadBody", "OnStoryEscapeJail", "OnStoryExploredLocation", "OnStoryFlatterNPC", "OnStoryHackTerminal", "OnStoryHello", "OnStoryIncreaseLevel", "OnStoryInfection", "OnStoryIntimidateNPC", "OnStoryIronSights", "OnStoryJail", "OnStoryKillActor", "OnStoryLocationLoaded", "OnStoryMineExplosion", "OnStoryNewVoicePower", "OnStoryPayFine", "OnStoryPickLock", "OnStoryPickPocket", "OnStoryPiracyActor", "OnStoryPlayerGetsFavor", "OnStoryRelationshipChange", "OnStoryRemoveFromPlayer", "OnStoryScript", "OnStoryServedTime", "OnStoryShipDock", "OnStoryShipLanding", "OnStoryTrespass", "OnTerminalMenuEnter", "OnTerminalMenuItemRun", "OnTimer", "OnTimerGameTime", "OnTrackedStatsEvent", "OnTranslationAlmostComplete", "OnTranslationComplete", "OnTranslationFailed", "OnTrapHitStart", "OnTrapHitStop", "OnTriggerEnter", "OnTriggerLeave", "OnTutorialEvent", "OnUnequipped", "OnUnload", "OnWorkshopCargoLinkChanged", "OnWorkshopFlyCam", "OnWorkshopMode", "OnWorkshopNPCTransfer", "OnWorkshopObjectGrabbed", "OnWorkshopObjectMoved", "OnWorkshopObjectPlaced", "OnWorkshopObjectRemoved", "OnWorkshopOutputLink", }; static const std::vector<std::string> EventNamesLowerCase = { "onaction", "onactivate", "onactoractivatedref", "onactorvaluechanged", "onactorvaluegreaterthan", "onactorvaluelessthan", "onaffinityevent", "onaffinityeventsent", "onaliaschanged", "onaliasinit", "onaliasreset", "onaliasshutdown", "onaliasstarted", "onanimationevent", "onanimationeventunregistered", "onbegin", "onbeginstate", "onbuildermenuselect", "oncellattach", "oncelldetach", "oncellload", "onchallengecompleted", "onchange", "onclose", "oncombatlistadded", "oncombatlistremoved", "oncombatstatechanged", "oncommandmodecompletecommand", "oncommandmodeenter", "oncommandmodeexit", "oncommandmodegivecommand", "oncompaniondismiss", "onconsciousnessstatechanged", "oncontainerchanged", "oncrewassigned", "oncrewdismissed", "oncripple", "ondeath", "ondeferredkill", "ondestroyed", "ondestructionstagechanged", "ondifficultychanged", "ondistancegreaterthan", "ondistancelessthan", "ondying", "oneffectfinish", "oneffectstart", "onend", "onendstate", "onenterbleedout", "onenterfurniture", "onenteroutpostbeaconmode", "onentershipinterior", "onentersneaking", "onentryrun", "onequipped", "onescortwaitstart", "onescortwaitstop", "onexitfurniture", "onexitshipinterior", "ongainlos", "ongetup", "ongrab", "onhit", "onhomeshipset", "oninit", "onitemadded", "onitemequipped", "onitemremoved", "onitemunequipped", "onkill", "onload", "onlocationchange", "onlocationexplored", "onlocationloaded", "onlockstatechanged", "onlostlos", "onmagiceffectapply", "onmapmarkerdiscovered", "onmenuopencloseevent", "onmissionaccepted", "onobjectdestroyed", "onobjectrepaired", "onopen", "onoutpostitempoweroff", "onoutpostitempoweron", "onoutpostplaced", "onpackagechange", "onpackageend", "onpackagestart", "onpartialcripple", "onphasebegin", "onphaseend", "onpicklock", "onpickpocketfailed", "onpipboyradiodetection", "onplanetsiteselectevent", "onplayerarrested", "onplayerassaultactor", "onplayerbuyship", "onplayercompleteresearch", "onplayercraftitem", "onplayercreaterobot", "onplayercrimegold", "onplayerdialoguetarget", "onplayerentervertibird", "onplayerfailedplotroute", "onplayerfalllongdistance", "onplayerfireweapon", "onplayerfollowerwarp", "onplayerhealteammate", "onplayeritemadded", "onplayerjail", "onplayerloadgame", "onplayerloiteringbegin", "onplayerloiteringend", "onplayermodarmorweapon", "onplayermodifiedship", "onplayermodrobot", "onplayermurderactor", "onplayerpayfine", "onplayerplanetsurveycomplete", "onplayerscannedobject", "onplayersellship", "onplayersleepstart", "onplayersleepstop", "onplayerswimming", "onplayerteleport", "onplayertrespass", "onplayeruseworkbench", "onplayerwaitstart", "onplayerwaitstop", "onpoweroff", "onpoweron", "onquestinit", "onquestrejected", "onquestshutdown", "onqueststarted", "onquesttimerend", "onquesttimermod", "onquesttimerpause", "onquesttimerresume", "onquesttimerstart", "onquickcontaineropened", "onraceswitchcomplete", "onradiationdamage", "onread", "onrecoverfrombleedout", "onrelease", "onreset", "onscanned", "onsell", "onshipbought", "onshipdock", "onshipfartravel", "onshipgravjump", "onshiplanding", "onshiprampdown", "onshiprefueled", "onshipscan", "onshipsold", "onshipsystemdamaged", "onshipsystempowerchange", "onshipsystemrepaired", "onshiptakeoff", "onshipundock", "onsit", "onspeechchallengeavailable", "onspeechchallengecompletion", "onspellcast", "onstageset", "onstarmaptargetselectevent", "onstart", "onstoryactivateactor", "onstoryactorattach", "onstoryaddtoplayer", "onstoryarrest", "onstoryassaultactor", "onstoryattractionobject", "onstorybribenpc", "onstorycastmagic", "onstorychangelocation", "onstorycraftitem", "onstorycrimegold", "onstorycure", "onstorydialogue", "onstorydiscoverdeadbody", "onstoryescapejail", "onstoryexploredlocation", "onstoryflatternpc", "onstoryhackterminal", "onstoryhello", "onstoryincreaselevel", "onstoryinfection", "onstoryintimidatenpc", "onstoryironsights", "onstoryjail", "onstorykillactor", "onstorylocationloaded", "onstorymineexplosion", "onstorynewvoicepower", "onstorypayfine", "onstorypicklock", "onstorypickpocket", "onstorypiracyactor", "onstoryplayergetsfavor", "onstoryrelationshipchange", "onstoryremovefromplayer", "onstoryscript", "onstoryservedtime", "onstoryshipdock", "onstoryshiplanding", "onstorytrespass", "onterminalmenuenter", "onterminalmenuitemrun", "ontimer", "ontimergametime", "ontrackedstatsevent", "ontranslationalmostcomplete", "ontranslationcomplete", "ontranslationfailed", "ontraphitstart", "ontraphitstop", "ontriggerenter", "ontriggerleave", "ontutorialevent", "onunequipped", "onunload", "onworkshopcargolinkchanged", "onworkshopflycam", "onworkshopmode", "onworkshopnpctransfer", "onworkshopobjectgrabbed", "onworkshopobjectmoved", "onworkshopobjectplaced", "onworkshopobjectremoved", "onworkshopoutputlink", }; } }
40,454
C++
.h
1,181
22.887384
69
0.547337
Orvid/Champollion
106
20
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,738
GuardStatement.hpp
Orvid_Champollion/Decompiler/Node/GuardStatement.hpp
#pragma once #include <cassert> #include <cstdint> #include <memory> #include "Base.hpp" #include "FieldNodeMixin.hpp" #include "Scope.hpp" #include "Visitor.hpp" namespace Node { class GuardStatement final : public Base, public FieldParametersNodeMixin<0>, public FieldBodyNodeMixin<1> { public: GuardStatement(size_t ip, BasePtr body) : Base(2, ip, 10), FieldParametersNodeMixin(this, std::make_shared<Params>()), FieldBodyNodeMixin(this, body) { } virtual ~GuardStatement() = default; void visit(Visitor* visitor) override { assert(visitor); visitor->visit(this); } void computeInstructionBounds() override { Base::computeInstructionBounds(); } }; }
876
C++
.h
33
18.787879
75
0.593301
Orvid/Champollion
106
20
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,752
EndGuard.hpp
Orvid_Champollion/Decompiler/Node/EndGuard.hpp
#pragma once #include <cassert> #include <cstdint> #include <memory> #include "Base.hpp" #include "FieldNodeMixin.hpp" #include "Scope.hpp" #include "Visitor.hpp" namespace Node { class EndGuard final : public Base, public FieldParametersNodeMixin<0> { public: EndGuard(size_t ip) : Base(1, ip, 10), FieldParametersNodeMixin(this, std::make_shared<Params>()) { } virtual ~EndGuard() = default; void visit(Visitor* visitor) override { assert(visitor); visitor->visit(this); } void computeInstructionBounds() override { Base::computeInstructionBounds(); } }; }
754
C++
.h
31
17.032258
74
0.581006
Orvid/Champollion
106
20
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,767
CaselessCompare.h
Orvid_Champollion/Champollion/CaselessCompare.h
#include <string> inline int caselessCompare(const char *a, const char *b, size_t len) { #ifdef _WIN32 return _strnicmp(a, b, len); #else return strncasecmp(a, b, len); #endif } inline int caselessCompare(const char *a, const char *b) { #ifdef _WIN32 return _stricmp(a, b); #else return strcasecmp(a, b); #endif }
323
C++
.h
15
19.933333
70
0.71987
Orvid/Champollion
106
20
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,770
ByteSwap.hpp
Orvid_Champollion/Pex/ByteSwap.hpp
#include <type_traits> #include <cassert> // These are backported from STL C++23 constexpr uint16_t _Byteswap_ushort(const uint16_t _Val) noexcept { return static_cast<unsigned short>((_Val << 8) | (_Val >> 8)); } constexpr uint32_t _Byteswap_ulong(const uint32_t _Val) noexcept { return (_Val << 24) | ((_Val << 8) & 0x00FF'0000) | ((_Val >> 8) & 0x0000'FF00) | (_Val >> 24); } constexpr uint64_t _Byteswap_uint64(const uint64_t _Val) noexcept { return (_Val << 56) | ((_Val << 40) & 0x00FF'0000'0000'0000) | ((_Val << 24) & 0x0000'FF00'0000'0000) | ((_Val << 8) & 0x0000'00FF'0000'0000) | ((_Val >> 8) & 0x0000'0000'FF00'0000) | ((_Val >> 24) & 0x0000'0000'00FF'0000) | ((_Val >> 40) & 0x0000'0000'0000'FF00) | (_Val >> 56); } template <class... T> constexpr bool _always_false_assert = false; template <typename Integer, typename = std::enable_if_t<std::is_integral<Integer>::value>> constexpr Integer byteswap(const Integer _Val) noexcept { if constexpr (sizeof(Integer) == 1) { return _Val; } else if constexpr (sizeof(Integer) == 2) { return static_cast<Integer>(_Byteswap_ushort(static_cast<uint16_t>(_Val))); } else if constexpr (sizeof(Integer) == 4) { return static_cast<Integer>(_Byteswap_ulong(static_cast<uint32_t>(_Val))); } else if constexpr (sizeof(Integer) == 8) { return static_cast<Integer>(_Byteswap_uint64(static_cast<uint64_t>(_Val))); } else { static_assert(_always_false_assert<Integer>, "Unexpected integer size"); } } float byteswap_float(const float _Val) noexcept { float retVal; const auto pVal = reinterpret_cast<const char*>(& _Val); const auto pRetVal = reinterpret_cast<char*>(& retVal); const std::size_t size = sizeof(float); assert(size == 4); for (std::size_t i = 0; i < size; i++) { pRetVal[size - 1 - i] = pVal[i]; } return retVal; }
1,937
C++
.h
42
41.214286
110
0.627316
Orvid/Champollion
106
20
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,776
Guard.hpp
Orvid_Champollion/Pex/Guard.hpp
#pragma once #include <cstdint> #include <vector> #include "StringTable.hpp" #include "NamedItem.hpp" namespace Pex { /** * @brief Guard definition * * This class contains the names guard. * */ class Guard : public NamedItem { public: Guard() = default; ~Guard() = default; }; typedef std::vector<Guard> Guards; }
336
C++
.h
20
14.7
39
0.710611
Orvid/Champollion
106
20
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,787
Binary.hpp
Orvid_Champollion/Pex/Binary.hpp
#pragma once #include <string> #include "Header.hpp" #include "StringTable.hpp" #include "DebugInfo.hpp" #include "UserFlag.hpp" #include "Object.hpp" namespace Pex { /** * @brief Pex main data structure * * The Binary class reflect the content of a PEX file. * */ class FileReader; class Binary { public: enum ScriptType { Unknown = -1, SkyrimScript, Fallout4Script, Fallout76Script, StarfieldScript }; Binary(); virtual ~Binary(); const Header& getHeader() const; Header& getHeader(); const StringTable& getStringTable() const; StringTable& getStringTable(); const DebugInfo& getDebugInfo() const; DebugInfo& getDebugInfo(); const UserFlags& getUserFlags() const; UserFlags& getUserFlags(); const Objects& getObjects() const; Objects& getObjects(); ScriptType getGameType() const; void sort(); protected: friend FileReader; void setScriptType(ScriptType game_type); Header m_Header; StringTable m_StringTable; DebugInfo m_DebugInfo; UserFlags m_UserFlags; Objects m_Objects; ScriptType m_ScriptType; }; }
1,164
C++
.h
50
19.14
54
0.703097
Orvid/Champollion
106
20
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,789
print-dev.cpp
hiramvillarreal_iotpos/printing/print-dev.cpp
/************************************************************************** * Copyright (C) 2009 by Miguel Chavez Gamboa * * hiramvillarreal.ap@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "print-dev.h" #include <QString> #include <QFile> #include <QIODevice> #include <QTextStream> #include <QTextCodec> bool PrintDEV::printSmallBalance(const QString &dev, const QString &codec, const QString &lines) { bool result = false; QFile file(dev); if (file.open(QIODevice::ReadWrite)) { QTextStream out(&file); if (codec.length() != 0) out.setCodec(QTextCodec::codecForName(codec.toLatin1())); else out.setCodec(QTextCodec::codecForName("UTF-8")); out << "\x1b\x4b\x30"; // Feed back x30 dot lines out << "\x1b\x4b\x20"; // Feed back x20 dot lines out << lines; // Print data out << "\x1b\x64\x06"; // Feed 6 lines file.close(); result = true; // result can be: file.close() result... } return result; } bool PrintDEV::printSmallTicket(const QString &dev, const QString &codec, const QString &lines) { bool result = printSmallBalance(dev, codec, lines); //it is the same code! return result; }
2,477
C++
.cpp
47
50.531915
96
0.515052
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
752,790
print-cups.cpp
hiramvillarreal_iotpos/printing/print-cups.cpp
/************************************************************************** * Copyright (C) 2009-2012 by Miguel Chavez Gamboa * * hiramvillarreal.ap@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "print-cups.h" #include "../src/misc.h" #include <QString> #include <QFont> #include <QtGui/QPrinter> #include <QPainter> #include <QLocale> #include <QDebug> bool PrintCUPS::printSmallBalance(const PrintBalanceInfo &pbInfo, QPrinter &printer) { bool result = false; // calculate font size int headerSize = printer.width()/16; //divisor found by trying, maybe has to do with font metrics? int textSize = headerSize/2; //i think the half of header size is ok if (printer.widthMM() > 150) printer.setPaperSize(QSizeF(104,110), QPrinter::Millimeter); // Resetting to 104mm (4 inches) paper. //When i press "Properties" button on print dialog (qt/cups), and i cancel the dialog, then the size is set to 210mm.. i dont know why. // 210 mm is the size of A4 paper (209.90mm), which it seems to be the default size.. // It is curious that when selecting custom size, the edit boxes for entering size are disabled and with a default 0x0 size.. why? This causes error on printing. CUPS or qt guilty? if (printer.widthMM() > 72 ) { // The font is big in bigger papers. // For paper size of 104mm (4 in). NOTE:I dont know if there is a bigger paper size for thermal POS printers. // A proper aproach would be get technical details of the printer (resolution -- dots per inch/mm) and calculate font size according... a challenge. headerSize = printer.width()/18; textSize = headerSize/3; } qDebug()<<"Paper Width: "<<printer.widthMM()<<"mm"<<"; Page Width: "<<printer.width()<<"; calculated headerSize: "<<headerSize; QFont header = QFont("Impact", headerSize); const int Margin = printer.width()/40; int yPos = 0; QPainter painter; painter.begin( &printer ); QFontMetrics fm = painter.fontMetrics(); //NOTE from Qt for the drawText: The y-position is used as the baseline of the font QFont tmpFont = QFont("Bitstream Vera Sans", textSize); QPen normalPen = painter.pen(); QString text; QSize textWidth; if (pbInfo.logoOnTop) { // Store Logo QPixmap logo = pbInfo.storeLogo; if (pbInfo.storeLogo.width() > printer.width() ) logo = logo.scaledToWidth( printer.width() ); //scale to the size of the page. painter.drawPixmap(printer.width()/2 - (logo.width()/2), Margin, logo); yPos = yPos + logo.height(); // Store Name painter.setFont(header); text = pbInfo.storeName; fm = painter.fontMetrics(); textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); yPos = yPos + Margin + textWidth.height(); painter.drawText((printer.width()/2)-(textWidth.width()/2),yPos, text); tmpFont = QFont("Bitstream Vera Sans", textSize); tmpFont.setItalic(true); painter.setFont(tmpFont); fm = painter.fontMetrics(); text = pbInfo.storeAddr; textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); yPos = yPos + fm.lineSpacing(); painter.drawText((printer.width()/2)-(textWidth.width()/2), yPos, text); yPos = yPos + fm.lineSpacing(); } else { // Store Logo QPixmap logo = pbInfo.storeLogo; if (pbInfo.storeLogo.width() > printer.width()/2 ) logo = logo.scaledToWidth( printer.width()/2 ); //scale to half the size of the page. painter.drawPixmap(printer.width() - logo.width() - Margin, Margin*1.75, logo); // Store Name painter.setFont(header); text = pbInfo.storeName; fm = painter.fontMetrics(); textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText(Margin,Margin+textWidth.height(), text); // Store Address tmpFont = QFont("Bitstream Vera Sans", textSize); tmpFont.setItalic(true); painter.setFont(tmpFont); fm = painter.fontMetrics(); yPos = yPos + fm.lineSpacing()+(Margin*0.75); text = pbInfo.storeAddr; textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.setPen(Qt::darkGray); painter.drawText(Margin, yPos, text); yPos = yPos + fm.lineSpacing(); } //FIXME: Check for logo printing!!!! if no logo, text is missplaced... if (pbInfo.storeLogo.isNull()) yPos = yPos + Margin + fm.lineSpacing(); // Header line painter.setPen(QPen(Qt::black, Margin*0.25, Qt::SolidLine, Qt::FlatCap, Qt::RoundJoin)); painter.drawLine(Margin, yPos, printer.width()-Margin, yPos); yPos = yPos + fm.lineSpacing()+Margin; tmpFont = QFont("Bitstream Vera Sans", textSize); //FIXME: A little more bigger than normal text? Apr 12 2011. tmpFont.setItalic(true); painter.setFont(tmpFont); fm = painter.fontMetrics(); //USER and Terminal text = pbInfo.thTitle; textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText((printer.width()/2)-(textWidth.width()/2), yPos, text); // +textWidth.height()+15 yPos = yPos + 2*fm.lineSpacing(); //change font tmpFont = QFont("Bitstream Vera Sans", textSize*1.25); // bigger tmpFont.setItalic(true); painter.setFont(tmpFont); fm = painter.fontMetrics(); painter.setPen(normalPen); //Balance ID text = pbInfo.thBalanceId; textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText((printer.width()/2)-(textWidth.width()/2), yPos , text); //+textWidth.height() //Date tmpFont = QFont("Bitstream Vera Sans", textSize); painter.setFont(tmpFont); fm = painter.fontMetrics(); yPos = yPos + fm.lineSpacing()*2; text = pbInfo.startDate; textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText((printer.width()/2)-(textWidth.width()/2), yPos , text); //+textWidth.height() yPos = yPos + fm.lineSpacing(); text = pbInfo.endDate; textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText((printer.width()/2)-(textWidth.width()/2), yPos, text); // +textWidth.height() yPos = yPos + 2*fm.lineSpacing(); // drawer balance //painter.setPen(QPen(Qt::black, 5, Qt::SolidLine, Qt::FlatCap, Qt::RoundJoin)); int tmpOffset = (printer.width()/4); tmpFont.setBold(true); painter.setFont(tmpFont); fm = painter.fontMetrics(); text = pbInfo.thDeposit; textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText(Margin, yPos, text); //+textWidth.height() text = pbInfo.thIn; textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText(tmpOffset, yPos, text); //+textWidth.height() text = pbInfo.thOut; textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText(tmpOffset*2, yPos, text); text = pbInfo.thInDrawer; textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText((tmpOffset*3)-Margin, yPos, text); yPos = yPos + fm.lineSpacing(); painter.setPen(QPen(Qt::darkGray, 2, Qt::SolidLine, Qt::FlatCap, Qt::RoundJoin)); painter.drawLine(Margin, yPos, printer.width()-Margin, yPos); painter.setPen(normalPen); //The quantities tmpFont.setBold(false); painter.setFont(tmpFont); fm = painter.fontMetrics(); yPos = yPos + fm.lineSpacing(); text = pbInfo.initAmount; textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText(Margin, yPos, text); text = pbInfo.inAmount; textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText(tmpOffset, yPos, text); text = pbInfo.outAmount; textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText(tmpOffset*2, yPos, text); text = pbInfo.cashAvailable; textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText((tmpOffset*3)-Margin, yPos, text); //TRANSACTION DETAILS //TODO: // Instead of 'Pay With' we can use 'Tendered' to make more sense // It will be: Tr. Id Hour Amount Tendered Type // and Type only include the first two letter 'CA' for Cash and 'CC' for credit cards and 'DB' for Debit Cards yPos = yPos + 3*fm.lineSpacing(); //header tmpFont = QFont("Bitstream Vera Sans", textSize+2);//FIXME: A little more smaller than normal text? Apr 12 2011. tmpFont.setItalic(false); tmpFont.setBold(true); painter.setFont(tmpFont); fm = painter.fontMetrics(); text = pbInfo.thTitleDetails; textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText((printer.width()/2)-(textWidth.width()/2), yPos, text); tmpFont = QFont("Bitstream Vera Sans", textSize); tmpFont.setBold(true); painter.setFont(tmpFont); fm = painter.fontMetrics(); yPos = yPos + 2*fm.lineSpacing(); tmpOffset = printer.width()/5; text = pbInfo.thTrId; textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText(Margin, yPos, text); text = pbInfo.thTrTime; textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText(tmpOffset, yPos, text); text = pbInfo.thTrAmount; textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText((tmpOffset*2)-Margin*2, yPos, text); text = pbInfo.thTrPaidW; textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText((tmpOffset*3)+Margin*2, yPos, text); //text = pbInfo.thTrPayMethod; //textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); //painter.drawText(tmpOffset*4, yPos, text); //printer.width()-textWidth.width()-Margin, Margin + yPos +textWidth.height(), text); yPos = yPos + fm.lineSpacing(); painter.setPen(QPen(Qt::darkGray, 1, Qt::SolidLine, Qt::FlatCap, Qt::RoundJoin)); painter.drawLine(Margin, yPos, printer.width()-Margin,yPos); tmpFont.setBold(false); painter.setFont(tmpFont); fm = painter.fontMetrics(); painter.setPen(QPen(normalPen)); yPos = yPos + fm.lineSpacing(); bool drawNote = false; //Iterating each transaction foreach(QString trStr, pbInfo.trList) { QStringList data = trStr.split("|"); //we have 5 fields in the string [ORDER] ID, HOUR, AMOUNT, PAIDWITH, PAYMETHOD text = data.at(2); // AMOUNT text = text.remove("$ "); double amount = text.toDouble(); //qDebug()<<" TEXT AMOUNT:"<<text<<" double Amount:"<<amount; text = data.at(3); // PAID WITH text = text.remove("$ "); double paidWith = text.toDouble(); //qDebug()<<" TEXT PAID:"<<text<<" double PAID:"<<paidWith<<" ID:"<<data.at(0); QString idTxt; if (amount > paidWith) { idTxt = "*"+ data.at(0); // ID drawNote = true; } else idTxt = data.at(0); text = idTxt; textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText(Margin,yPos, text); text = data.at(1); // HOUR textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText(tmpOffset, yPos, text); text = data.at(2); // AMOUNT textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText((tmpOffset*2)-Margin*2, yPos, text); text = data.at(3) + data.at(4); // PAID WITH textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText((tmpOffset*3)+Margin*2, yPos, text); //text = data.at(4); // PAYMENT METHOD //textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); //painter.drawText(tmpOffset*4, yPos, text); //printer.width()-textWidth.width()-Margin, Margin + yPos +textWidth.height(), text); yPos = yPos + fm.lineSpacing()+Margin*.5; } //yPos = yPos + fm.lineSpacing()+Margin; painter.setPen(QPen(Qt::darkGray, 1, Qt::SolidLine, Qt::FlatCap, Qt::RoundJoin)); painter.drawLine(Margin, yPos, printer.width()-Margin,yPos); //Draw the Note about Reservations ( amount > paid ) if (drawNote) { yPos = yPos + fm.lineSpacing()*2; painter.setPen(QPen(normalPen)); fm = painter.fontMetrics(); text = "* " + pbInfo.reservationNote; // Adjust text width double maxLen = (printer.width())-Margin*1.5; QStringList tmpStr = Misc::stringToParagraph( text , fm, maxLen ); foreach(QString str, tmpStr) { painter.drawText(Margin, yPos, str); yPos = yPos + fm.lineSpacing(); } } //NOTE: Print a note for the payment type. yPos = yPos + fm.lineSpacing()*2; painter.drawText(Margin, yPos, "** "+ pbInfo.notCashNote); yPos = yPos + fm.lineSpacing(); // CASH FLOW DETAILS //NOTE: // The cashout type will be removed from ticket to save space, instead to indicate the type, the amount will be positive (cash-in) // or negative (cash-out). tmpOffset = printer.width()/5; if (!pbInfo.cfList.isEmpty()) { yPos = yPos + 2*fm.lineSpacing(); //2 lines for the title tmpFont = QFont("Bitstream Vera Sans", textSize+2); //FIXME: A little more bigger than normal text? Apr 12 2011. tmpFont.setItalic(true); tmpFont.setBold(true); painter.setPen(QPen(normalPen)); painter.setFont(tmpFont); fm = painter.fontMetrics(); text = pbInfo.thTitleCFDetails; textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText((printer.width()/2)-(textWidth.width()/2), yPos, text); tmpFont = QFont("Bitstream Vera Sans", textSize); //FIXME: A little more smaller than normal text? Apr 12 2011. tmpFont.setItalic(false); tmpFont.setBold(true); painter.setFont(tmpFont); fm = painter.fontMetrics(); yPos = yPos + 2*fm.lineSpacing(); //titles text = pbInfo.thTrId; textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText(Margin, yPos, text); text = pbInfo.thCFDate; textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText(tmpOffset-Margin*2, yPos, text); text = pbInfo.thTrAmount; textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText((tmpOffset*2)-Margin*2, yPos, text); text = pbInfo.thCFReason; textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText((tmpOffset*3)+Margin*3,yPos, text); //text = pbInfo.thCFType; //textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); //painter.drawText(tmpOffset*4, yPos, text); //printer.width()-textWidth.width()-Margin, Margin + yPos +textWidth.height(), text); yPos = yPos + fm.lineSpacing(); painter.setPen(QPen(Qt::darkGray, 2, Qt::SolidLine, Qt::FlatCap, Qt::RoundJoin)); painter.drawLine(Margin,yPos, printer.width()-Margin, yPos); tmpFont = QFont("Bitstream Vera Sans", textSize); tmpFont.setItalic(false); tmpFont.setBold(false); painter.setFont(tmpFont); painter.setPen(QPen(normalPen)); fm = painter.fontMetrics(); yPos =yPos + fm.lineSpacing(); //Iterating each cashflow foreach(QString cfStr, pbInfo.cfList) { QStringList data = cfStr.split("|"); //we have 5 fields in the string [ORDER] ID, TYPESTR, REASON, AMOUNT, DATE text = data.at(0); // ID textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText(Margin, yPos, text); text = data.at(4); // HOUR textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText(tmpOffset-Margin*2, yPos, text); text = data.at(1)+" "+data.at(3); // AMOUNT --here we add the sign to indicate it was IN+ or OUT-. textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText((tmpOffset*2)-Margin*2,yPos, text); text = data.at(2); // REASON while (fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text).width() >= printer.width()-5 ) { text.chop(2); } //textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText((tmpOffset*3)+Margin*3, yPos, text); //text = data.at(1); // TYPE //FIXME: Pass a parameter to indicate a cash-in or cash-out. Now we take the word 'cash in/out' // The text is stored in the database, so the admin can change this text using mysql (not iotstock)... //fm = painter.fontMetrics(); //while (fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text).width() >= printer.width()-Margin*1) { text.chop(2); } //(printer.width()-fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text).width()) //textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); //painter.drawText(tmpOffset*4, yPos, text); //printer.width()-textWidth.width()-Margin, Margin + yPos +textWidth.height(), text); yPos = yPos + fm.lineSpacing(); } } result = painter.end();// this makes the print job start return result; } // Paper size for a receipt: 72mm x 200mm (the height is just a number, because it is 'endless') // This code is meant to be used in receipt printers, which dont need page breaks. // The problem is when this code is sent to a PDF instead of a receipt printer (i.e. for testing and debugging) // Which i can solve by enable the printer.newPage() (uncommenting it on the products iterations where its mainly needed) bool PrintCUPS::printSmallTicket(const PrintTicketInfo &ptInfo, QPrinter &printer) { bool result = false; if (printer.widthMM() > 150) printer.setPaperSize(QSizeF(104,200), QPrinter::Millimeter); // Resetting to 104mm (4 inches) paper. //When i press "Properties" button on print dialog (qt/cups), and i cancel the dialog, then the size is set to 210mm.. i dont know why. // 210 mm is the size of A4 paper (209.90mm), which it seems to be the default size.. // It is curious that when selecting custom size, the edit boxes for entering size are disabled and with a default 0x0 size.. why? This causes error on printing. CUPS or qt guilty? //Setting fixed font size for every paper size. int headerSize = 15; int textSize = 7; //I think 7 is fine (for me). Small and readable. 8 is bigger but uses more space, precious space (horizontally). qDebug()<<"* PAPER SIZE"<<printer.paperSize(QPrinter::Inch)<<"Paper Width: "<<printer.widthMM()<<"mm"<<" Height:"<<printer.heightMM()<<"; Page Width: "<<printer.width()<<"; calculated headerSize: "<<headerSize<<" Text size:"<<textSize; QFont header = QFont("Impact", headerSize); const int Margin = printer.width()/40; //divisor found by trying int yPos = 0; QPainter painter; painter.begin( &printer ); QFontMetrics fm = painter.fontMetrics(); //NOTE from Qt for the drawText: The y-position is used as the baseline of the font // Header: Store Name, Store Address, Store Phone, Store Logo... QFont tmpFont = QFont("Bitstream Vera Sans", textSize); QPen normalPen = painter.pen(); QString text; QSize textWidth; if (ptInfo.logoOnTop) { // Store Logo QPixmap logo = ptInfo.storeLogo; if (ptInfo.storeLogo.width() > printer.width() ) logo = logo.scaledToWidth( printer.width() ); //scale to the size of the page. painter.drawPixmap(printer.width()/2 - (logo.width()/2), Margin, logo); yPos = yPos + logo.height(); // Store Name painter.setFont(header); text = ptInfo.storeName; fm = painter.fontMetrics(); textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); yPos = yPos + Margin + textWidth.height(); painter.drawText((printer.width()/2)-(textWidth.width()/2),yPos, text); // Store Address tmpFont = QFont("Bitstream Vera Sans", textSize); tmpFont.setItalic(true); painter.setFont(tmpFont); fm = painter.fontMetrics(); ///Aug 14 2011: If the user enters an '|' in the phone we will add a new line. The user is responsible for text width between new lines. QStringList lines = ptInfo.storePhone.split("|", QString::SkipEmptyParts); //remove first line to be attached to the ", Phone:". QString first = ""; if (!lines.isEmpty()) first = lines.takeFirst(); text = ptInfo.storeAddr + ", " +ptInfo.thPhone + first; //+ ptInfo.storePhone; textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); yPos = yPos + fm.lineSpacing(); painter.drawText((printer.width()/2)-(textWidth.width()/2), yPos, text); yPos = yPos + fm.lineSpacing(); //now we print the lines if any.. if (!lines.isEmpty()) { foreach(QString line, lines) { text = line; textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText((printer.width()/2)-(textWidth.width()/2) , yPos, text); yPos = yPos + fm.lineSpacing(); //ok now we inc yPos. } } } else { // Store Logo QPixmap logo = ptInfo.storeLogo; if (ptInfo.storeLogo.width() > printer.width()/2 ) logo = logo.scaledToWidth( printer.width()/2 ); //scale to half the size of the page. painter.drawPixmap(printer.width() - logo.width() - Margin, Margin*1.75, logo); // Store Name painter.setFont(header); text = ptInfo.storeName; fm = painter.fontMetrics(); textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText(Margin,Margin+textWidth.height(), text); // Store Address tmpFont.setItalic(true); painter.setFont(tmpFont); fm = painter.fontMetrics(); yPos = yPos + fm.lineSpacing()+(Margin*0.75); text = ptInfo.storeAddr + ", " +ptInfo.thPhone + ptInfo.storePhone; textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.setPen(Qt::darkGray); painter.drawText(Margin, Margin*2 + yPos + textWidth.height(), text); yPos = yPos + fm.lineSpacing()*2; } //FIXME: Check for logo printing!!!! if no logo, text is missplaced... if (ptInfo.storeLogo.isNull()) yPos = yPos + Margin + fm.lineSpacing(); // Header line painter.setPen(QPen(Qt::black, Margin*0.25, Qt::SolidLine, Qt::FlatCap, Qt::RoundJoin)); painter.drawLine(Margin, yPos, printer.width()-Margin, yPos); yPos = yPos + fm.lineSpacing()*2; //Date tmpFont = QFont("Bitstream Vera Sans", textSize); tmpFont.setItalic(false); painter.setFont(tmpFont); fm = painter.fontMetrics(); painter.setPen(normalPen); text = ptInfo.thDate ; textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText(Margin, yPos, text); //Ticket Number tmpFont.setBold(true); painter.setFont(tmpFont); fm = painter.fontMetrics(); text = ptInfo.thTicket; textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); //painter.drawText(printer.width() - textWidth.width() - Margin, yPos, text); yPos = yPos + fm.lineSpacing(); //Vendor, terminal number tmpFont.setBold(false); painter.setFont(tmpFont); fm = painter.fontMetrics(); text = ptInfo.salesPerson + ", " + ptInfo.terminal; textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText(Margin, yPos, text); yPos = yPos + 2*fm.lineSpacing(); //Print a RESERVATION header if is a starting Reservation. if (ptInfo.ticketInfo.isAReservation && ptInfo.ticketInfo.reservationStarted && !ptInfo.ticketInfo.hasSpecialOrders) { tmpFont = QFont("Bitstream Vera Sans", textSize); tmpFont.setItalic(true); tmpFont.setBold(true); painter.setFont(tmpFont); fm = painter.fontMetrics(); text = ptInfo.hdrReservation; textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText((printer.width()/2)-(textWidth.width()/2), yPos, text); yPos = yPos + fm.lineSpacing(); text = QString::number(ptInfo.ticketInfo.reservationId); textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText((printer.width()/2)-(textWidth.width()/2), yPos , text); //+textWidth.height() yPos = yPos + fm.lineSpacing()*2; } painter.setPen(Qt::black); tmpFont = QFont("Bitstream Vera Sans", textSize); tmpFont.setItalic(false); tmpFont.setBold(true); painter.setFont(tmpFont); fm = painter.fontMetrics(); // Texts needed to calculate the width used.. QString textTax = ptInfo.thTax; QString textTotal = ptInfo.thTotal; QString textPrice = ptInfo.thPrice; QString textQty = ptInfo.thQty; //textPrice; //ptInfo.thQty + " x " + textPrice; QString textDisc = ptInfo.thDiscount; //FIXME: Possible problems with TRANSLATED TEXTS, for example, Tax in Spanish is "Impuesto" but can be used "Imp", but translators DONT KNOW THIS. // Products Subheader OFFSETS int columnDesc = Margin*2 + (fm.size(Qt::TextExpandTabs | Qt::TextDontClip, textQty).width()); int columnTotal= printer.width() - 5*Margin - (fm.size(Qt::TextExpandTabs | Qt::TextDontClip, textTotal).width()); //Printing Qty painter.drawText(Margin, Margin+yPos, textQty); //Printing Product painter.drawText(columnDesc,Margin+yPos, ptInfo.thProduct); //Printing TOTALS painter.drawText(columnTotal, Margin + yPos, textTotal); yPos = yPos + fm.lineSpacing(); painter.setPen(QPen(Qt::darkGray, 1, Qt::SolidLine, Qt::FlatCap, Qt::RoundJoin)); painter.drawLine(Margin, yPos, printer.width()-Margin, yPos); painter.setPen(normalPen); tmpFont = QFont("Bitstream Vera Sans", textSize ); painter.setFont(tmpFont); yPos = yPos + fm.lineSpacing(); // End of Header Information. // Content : Each product QLocale localeForPrinting; for (int i = 0; i < ptInfo.ticketInfo.lines.size(); ++i) { TicketLineInfo tLine = ptInfo.ticketInfo.lines.at(i); QDateTime deliveryDT = ptInfo.ticketInfo.lines.at(i).deliveryDateTime; QString idesc = tLine.desc; QString iprice = localeForPrinting.toString(tLine.price,'f',2); QString iqty = localeForPrinting.toString(tLine.qty, 'f', 2); QString itax = ""; if (tLine.tax <= 0) itax = "E"; else itax = localeForPrinting.toString(tLine.tax, 'f', 2); // We must be aware of the locale. europe uses ',' instead of '.' as the decimals separator. // note: QLocale has a method that does this locale aware! if the locale is set correctly //NOTE: CHop trailing zeroes to SAVE SPACE!!!! TODO:Does anyone wants them back??? if (iqty.endsWith(".00") || iqty.endsWith(",00")) { iqty.chop(3); iqty += ""; /*xqty++;*/}//we chop the trailing zeroes... if (itax.endsWith(".00") || itax.endsWith(",00")) { itax.chop(3); }//we chop the trailing zeroes... //if (iprice.endsWith(".00") || iprice.endsWith(",00")) { iprice.chop(3); }//we chop the trailing zeroes... if (itax != "E" ) itax += " %"; //FIXME: Si en el ticket hay solo cantidades enteras, entonces hay espacios en blanco de los choped zeroes. // Y asi toma mucho espacio... poner los espacios en blanco solo si hay uno que no termine en .00 // Pero no hay forma de saberlo sin hacer una iteracion extra... //if ( i == ptInfo.ticketInfo.lines.size()-1 && xqty == i) //iqty = iqty + tLine.unitStr; QString idiscount = localeForPrinting.toString(-(/*tLine.qty**/tLine.disc),'f',2); if (tLine.disc <= 0) idiscount = ""; // dont print 0.0 //if (idiscount.endsWith(".00") || idiscount.endsWith(",00")) { idiscount.chop(3); }//we chop the trailing zeroes... QString idue = localeForPrinting.toString(tLine.total,'f',2); //if (idue.endsWith(".00") || idue.endsWith(",00")) { idue.chop(3); }//we chop the trailing zeroes... while (fm.size(Qt::TextExpandTabs | Qt::TextDontClip, idesc).width()+columnDesc >= columnTotal/* - Margin*/) { idesc.chop(1); } //first print the qty. text = iqty+" x"; painter.drawText(Margin, Margin+yPos, text); //product description... painter.drawText(columnDesc, Margin+yPos, idesc); painter.drawText(columnTotal, Margin+yPos, idue); yPos = yPos + fm.lineSpacing(); ///Second line. Aug 14 2011. Printing unitary price, discounts, taxes QString discc = ""; if (idiscount > 0) { discc = ", "+idiscount+" "+textDisc; } text = "@ "+iprice+ ", "+itax+ " "+ textTax + discc; painter.drawText(Margin*5, Margin + yPos, text); yPos = yPos + fm.lineSpacing(); ///check if there is a Special Order or group, to print contents if ( !tLine.geForPrint.isEmpty() ) { QStringList tmpList = tLine.geForPrint.split("|"); QStringList strList; tmpList.removeFirst(); //check text lenght double maxL = ((printer.width())-Margin*2); foreach(QString strTmp, tmpList) { fm = painter.fontMetrics(); QString strCopy = strTmp; double realTrozos = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, strTmp).width() / maxL; int trozos = realTrozos; double diff = (realTrozos - trozos); if (diff > 0.25 && trozos > 0) trozos += 1; int tamTrozo = 0; if (trozos > 0) { tamTrozo = (strTmp.length()/trozos); } else { tamTrozo = strTmp.length(); } QStringList otherList; for (int x = 1; x <= trozos; x++) { //we repeat for each trozo if (x*(tamTrozo-1) < strCopy.length()) strCopy.insert(x*(tamTrozo-1), "| "); //create a section otherList = strCopy.split("|"); } if (!otherList.isEmpty()) strList << otherList; if (trozos < 1) strList << strTmp; //qDebug()<<"Trozos:"<<trozos<<" tamTrozo:"<<tamTrozo<<" realTrozos:"<<QString::number(realTrozos,'f', 2)<<" maxL:"<<maxL<<" strTmp.width in pixels:"<<fm.size(Qt::TextExpandTabs | Qt::TextDontClip, strTmp).width()<<" diff:"<<diff; } foreach(QString str, strList) { painter.drawText(Margin, Margin+yPos, str); yPos = yPos + fm.lineSpacing(); } //is payment complete? // if ( Margin + yPos > printer.height() - Margin ) { // printer.newPage(); // no more room on this page // yPos = 0; // back to top of page // } } /// is group or specialorder ? //Check if space for the next text line // if ( Margin + yPos > printer.height() - Margin ) { // printer.newPage(); // no more room on this page // yPos = 0; // back to top of page // } } //for each item //NOTE: Is it really needed to print a line with the discount? // The discount amount is printed at the end (totals). //Check for client discount //if (ptInfo.clientDiscMoney > 0) { // text = ptInfo.clientDiscountStr; // tmpFont.setWeight(QFont::Bold); // tmpFont.setItalic(true); // painter.setFont(tmpFont); // painter.drawText(Margin, Margin + yPos , text); // text = localeForPrinting.toString(-ptInfo.clientDiscMoney,'f',2); // painter.drawText(columnDisc, Margin + yPos , text); //printer.width()/3)+columnDisc-50 // yPos = yPos + fm.lineSpacing(); // tmpFont.setWeight(QFont::Normal); // tmpFont.setItalic(false); // painter.setFont(tmpFont); //} //line separator.. yPos += Margin; painter.setPen(QPen(Qt::darkGray, 1, Qt::SolidLine, Qt::FlatCap, Qt::RoundJoin)); painter.drawLine(Margin, yPos, printer.width()-Margin, yPos); //Check if space for the next text 3 lines // if ( (Margin + yPos +fm.lineSpacing()*3) > printer.height() - Margin ) { // printer.newPage(); // no more room on this page // yPos = 0; // back to top of page // } //total Articles... painter.setPen(normalPen); tmpFont.setWeight(QFont::Bold); painter.setFont(tmpFont); yPos = yPos + fm.lineSpacing(); text = ptInfo.thArticles; painter.drawText(Margin, Margin + yPos , text); yPos = yPos + fm.lineSpacing(); //RESERVATION STUFF bool isAReservation = ptInfo.ticketInfo.isAReservation; double resPayment = ptInfo.ticketInfo.reservationPayment; if (isAReservation && !ptInfo.ticketInfo.hasSpecialOrders) { QLocale locale; QString sp; QString spQty; tmpFont = QFont("Bitstream Vera Sans", textSize); tmpFont.setWeight(QFont::Bold); painter.setFont(tmpFont); fm = painter.fontMetrics(); yPos = yPos + Margin; //just a small space.. // PURCHASE AMOUNT sp = ptInfo.resTotalAmountStr; spQty = locale.toString(ptInfo.ticketInfo.purchaseTotal, 'f',2); textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, sp); painter.drawText(printer.width()-(printer.width()/3)-textWidth.width(), Margin+yPos, sp); textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, spQty); painter.drawText((printer.width() - textWidth.width() - Margin), Margin+yPos, spQty); yPos = yPos + fm.lineSpacing(); // PRE PAYMENT. sp = ptInfo.paymentStrPrePayment; spQty = locale.toString(resPayment,'f',2); // THE AMOUNT PRE PAID textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, sp); painter.drawText(printer.width()-(printer.width()/3)-textWidth.width(), Margin+yPos, sp); textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, spQty); painter.drawText((printer.width() - textWidth.width() - Margin), Margin+yPos, spQty); yPos = yPos + fm.lineSpacing()*3; ///NOTE:The taxes are not added to the ticket when reservation starts. When reservation is finished this taxes are added to the // total. This could cause confusions, because at the first ticket printed (when reservation started) the total does not // include the taxes and in the final ticket it does include taxes. Even the transaction itself when the reservation starts // does not include taxes (totalTaxes=0). NOTE 2: Verify with both Settings::addTaxes(). When addTaxes()==false, then the // prices will embed the tax and this is not a problem (not verified). // We could include a text in the ticket explaining in both tickets that the taxes are included ONLY in the final ticket. } // NOW SPECIAL ORDERS STUFF //BEGIN The PRE-PAYMENT/NEXT-PAYMENT DATA. bool isSO = ptInfo.ticketInfo.hasSpecialOrders; bool isCompletingSO = ptInfo.ticketInfo.completingSpecialOrder; QLocale locale; if (isSO) { QString sp; QString sp2; QString spQty; QString sp2Qty; if (isCompletingSO) { sp = ptInfo.paymentStrComplete; spQty = locale.toString(ptInfo.ticketInfo.total,'f',2); // THE DEBT of the SO. sp2 = ptInfo.lastPaymentStr; sp2Qty = locale.toString(ptInfo.ticketInfo.soTotal - ptInfo.ticketInfo.total , 'f',2); // the prepayment } else { // SO is in pre payment sp = ptInfo.paymentStrPrePayment; spQty = locale.toString(ptInfo.ticketInfo.total, 'f',2); // prepayment sp2 = ptInfo.nextPaymentStr; sp2Qty = locale.toString(ptInfo.ticketInfo.soTotal-ptInfo.ticketInfo.total, 'f',2); // Next payment } if (!isSO) sp = ""; ///hack! //change font for the PAYMENT MSG tmpFont = QFont("Bitstream Vera Sans", textSize ); tmpFont.setWeight(QFont::Bold); painter.setFont(tmpFont); fm = painter.fontMetrics(); textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, sp); painter.drawText(printer.width()-(printer.width()/3)-textWidth.width(), Margin+yPos, sp); textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, spQty); painter.drawText((printer.width() - textWidth.width() - Margin), Margin+yPos, spQty); yPos = yPos + fm.lineSpacing(); //print the negative qty for the payment. // The negative qty is one of the next: // * When completing the SO: the amount of the pre-payment. // * When starting the SO: the remaining amount to pay. sp2 = (ptInfo.ticketInfo.soTotal-ptInfo.ticketInfo.total >0) ? sp2 : ""; if (!isSO) sp2 = ""; ///hack! textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, sp2); painter.drawText(printer.width()-(printer.width()/3)-textWidth.width(), Margin+yPos, sp2); textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, sp2Qty); painter.drawText((printer.width() - textWidth.width() - Margin), Margin+yPos, sp2Qty); yPos = yPos + fm.lineSpacing(); ///Check for delivery date and if its a SO if (isSO) { sp = ptInfo.deliveryDateStr; // + deliveryDT.toString("ddd d MMMM, h:m ap"); //TODO:hey i18n stuff!!! tmpFont = QFont("Bitstream Vera Sans", textSize ); tmpFont.setWeight(QFont::Bold); painter.setFont(tmpFont); fm = painter.fontMetrics(); textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, sp); painter.drawText(printer.width()-(printer.width()/3)-textWidth.width(), Margin+yPos, sp); sp = ptInfo.ticketInfo.deliveryDT.toString("ddd d MMM"); textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, sp); painter.drawText((printer.width() - textWidth.width() - Margin), Margin+yPos, sp); sp = ptInfo.ticketInfo.deliveryDT.toString("h:m ap"); yPos = yPos + fm.lineSpacing(); textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, sp); painter.drawText((printer.width() - textWidth.width() - Margin), Margin+yPos, sp); yPos = yPos + fm.lineSpacing(); } yPos = yPos + fm.lineSpacing()*2; //END The PRE-PAYMENT/NEXT-PAYMENT DATA. } tmpFont = QFont("Bitstream Vera Sans", textSize ); tmpFont.setWeight(QFont::Normal); painter.setFont(tmpFont); fm = painter.fontMetrics(); //NOTE: //When starting a reservation, the amount paid is only an advance payment, not the whole. //When complelting the reservation (payment) the taxes are added to the remaining amount to pay. //So, when starting the reservation, we do not print details about taxes (subtotal taxes and total) //because those amounts will not check. //When completing reservation, the details WILL be printed. //ALSO SEE NOTE on the balance printing when are reservations in the transactions. bool printDetails = true; if (ptInfo.ticketInfo.isAReservation && ptInfo.ticketInfo.reservationStarted) printDetails = false; if ( printDetails ) { //subtotals textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, ptInfo.thSubtotal); painter.drawText(printer.width()-(printer.width()/3)-textWidth.width(), Margin+yPos, ptInfo.thSubtotal); textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, ptInfo.subtotal); painter.drawText((printer.width() - textWidth.width() - Margin), Margin+yPos, ptInfo.subtotal); yPos = yPos + fm.lineSpacing(); if (ptInfo.totDisc >0) { textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, ptInfo.thDiscount); painter.drawText(printer.width()-(printer.width()/3)-textWidth.width(), Margin+yPos, ptInfo.thDiscount); textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, ptInfo.tDisc); painter.drawText((printer.width() - textWidth.width() - Margin), Margin+yPos, ptInfo.tDisc); yPos = yPos + fm.lineSpacing(); } //taxes textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, ptInfo.thTax); painter.drawText(printer.width()-(printer.width()/3)-textWidth.width(), Margin+yPos, ptInfo.thTax); textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, ptInfo.taxes); painter.drawText((printer.width() - textWidth.width() - Margin), Margin+yPos, ptInfo.taxes); yPos = yPos + fm.lineSpacing(); //draw a total line painter.setPen(QPen(Qt::darkGray, 1, Qt::SolidLine, Qt::FlatCap, Qt::RoundJoin)); painter.drawLine((printer.width() - (printer.width()/3)) , yPos, printer.width()-Margin, yPos); yPos = yPos + fm.lineSpacing(); painter.setPen(QPen(Qt::black, 1, Qt::SolidLine, Qt::FlatCap, Qt::RoundJoin)); //grand total tmpFont = QFont("Bitstream Vera Sans", textSize ); tmpFont.setWeight(QFont::Bold); painter.setFont(tmpFont); fm = painter.fontMetrics(); textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, ptInfo.thTotal); painter.drawText(printer.width()-(printer.width()/3)-textWidth.width(), Margin+yPos, ptInfo.thTotal); textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, ptInfo.thTotals); painter.drawText((printer.width() - textWidth.width() - Margin), Margin+yPos, ptInfo.thTotals); } yPos = yPos + fm.lineSpacing()*2; // Tendered with and change tmpFont = QFont("Bitstream Vera Sans", textSize ); tmpFont.setWeight(QFont::Normal); painter.setFont(tmpFont); fm = painter.fontMetrics(); //TENDERED textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, ptInfo.thTendered); painter.drawText(printer.width()-(printer.width()/3)-textWidth.width(), Margin+yPos, ptInfo.thTendered); textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, ptInfo.thPaid); painter.drawText((printer.width() - textWidth.width() - Margin), Margin+yPos, ptInfo.thPaid); yPos = yPos + fm.lineSpacing(); //CHANGE textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, ptInfo.thChangeStr); painter.drawText(printer.width()-(printer.width()/3)-textWidth.width(), Margin+yPos, ptInfo.thChangeStr); textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, ptInfo.thChange); painter.drawText((printer.width() - textWidth.width() - Margin), Margin+yPos, ptInfo.thChange); yPos = yPos + fm.lineSpacing(); //TODO: Verify THIS!!! if (ptInfo.ticketInfo.paidWithCard) { painter.setFont(tmpFont); text = ptInfo.thCard; painter.drawText(Margin, Margin + yPos , text); yPos = yPos + fm.lineSpacing(); painter.setFont(tmpFont); text = ptInfo.thCardAuth; painter.drawText(Margin, Margin + yPos , text); yPos = yPos + fm.lineSpacing(); } //Points if is not the default user TODO: configure this to allow or not to print this info in case the store does not use points if (ptInfo.ticketInfo.clientid > 1) { //no default user yPos = yPos + fm.lineSpacing(); QStringList strPoints = ptInfo.thPoints.split("|"); foreach(QString strTmp, strPoints) { painter.drawText(Margin, Margin+yPos, strTmp); yPos = yPos + fm.lineSpacing(); } } // if ( (Margin + yPos +fm.lineSpacing()*2) > printer.height() - Margin ) { // printer.newPage(); // no more room on this page // yPos = 0; // back to top of page // } //Random Message double maxL = ((printer.width())-Margin*2); QStringList strList; QString strTmp = ptInfo.randomMsg; if (!ptInfo.randomMsg.isEmpty()) { tmpFont = QFont("Bitstream Vera Sans", textSize); tmpFont.setItalic(true); painter.setFont(tmpFont); fm = painter.fontMetrics(); yPos = yPos + fm.lineSpacing()*2; //fixing message lenght QString strCopy = strTmp; double realTrozos = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, strTmp).width() / maxL; int trozos = realTrozos; double diff = (realTrozos - trozos); if (diff > 0.25 && trozos > 0) trozos += 1; int tamTrozo = 0; if (trozos > 0) { tamTrozo = (strTmp.length()/trozos); } else { tamTrozo = strTmp.length(); } QStringList otherList; for (int x = 1; x <= trozos; x++) { //we repeat for each trozo if (x*(tamTrozo-1) < strCopy.length()) strCopy.insert(x*(tamTrozo-1), "| "); //create a section otherList = strCopy.split("|"); } if (!otherList.isEmpty()) strList << otherList; if (trozos < 1) strList << strTmp; //qDebug()<<"rm : Trozos:"<<trozos<<" tamTrozo:"<<tamTrozo<<" realTrozos:"<<QString::number(realTrozos,'f', 2)<<" maxL:"<<maxL<<" strTmp.width in pixels:"<<fm.size(Qt::TextExpandTabs | Qt::TextDontClip, strTmp).width()<<" diff:"<<diff; //end if fixing the lenght of the message. foreach(QString str, strList) { painter.drawText(Margin, Margin+yPos, str); yPos = yPos + fm.lineSpacing(); } } //Draw the ticket number as a barcode (code 39) http://es.wikipedia.org/wiki/Code_39 painter.setFont(QFont("Free 3 of 9", 22)); //Only numbers. fm = painter.fontMetrics(); yPos = yPos + fm.lineSpacing()*2; QString code = ptInfo.thTicket; //remove all chars that we do not want on barcodes (#, space, colons, dots ). This strings comes formated, that's why we need to 'unformat it' code.remove(QChar('#'), Qt::CaseSensitive); code.remove(QChar(' '), Qt::CaseSensitive); code.remove(QChar(','), Qt::CaseSensitive); code.remove(QChar('.'), Qt::CaseSensitive); code = "*"+code+"*"; //for code 39 to work. //painter.drawText((printer.width()/2)-(fm.size(Qt::TextExpandTabs | Qt::TextDontClip, code).width()/2)-Margin, Margin+yPos, code); //now draw the number in text (no barcode) below. tmpFont = QFont("Bitstream Vera Sans", textSize); painter.setFont(tmpFont); fm = painter.fontMetrics(); yPos = yPos + fm.lineSpacing()*1; code.remove(QChar('*'), Qt::CaseSensitive); painter.drawText((printer.width()/2)-(fm.size(Qt::TextExpandTabs | Qt::TextDontClip, code).width()/2)-Margin, Margin+yPos, code); // The ticket message (tanks...) tmpFont = QFont("Bitstream Vera Sans", textSize); tmpFont.setItalic(true); painter.setFont(tmpFont); fm = painter.fontMetrics(); yPos = yPos + fm.lineSpacing()*2; painter.drawText((printer.width()/2)-(fm.size(Qt::TextExpandTabs | Qt::TextDontClip, ptInfo.ticketMsg).width()/2)-Margin, Margin+yPos, ptInfo.ticketMsg); result = painter.end();// this makes the print job start return result; } bool PrintCUPS::printBigTicket(const PrintTicketInfo &ptInfo, QPrinter &printer) { bool result = false; QFont header = QFont("Impact", 30); QFont sectionHeader = QFont("Bitstream Vera Sans", 14); const int Margin = 30; QPainter painter; painter.begin( &printer ); int yPos = 0; QFontMetrics fm = painter.fontMetrics(); // Header: Store Name, Store Address, Store Phone, Store Logo... painter.setFont(header); QString text = ptInfo.storeName; QSize textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText(Margin,Margin*2+textWidth.height(), text); yPos = yPos + fm.lineSpacing(); // Store Address QFont tmpFont = QFont("Bitstream Vera Sans", 10); tmpFont.setItalic(true); painter.setFont(tmpFont); fm = painter.fontMetrics(); QPen normalPen = painter.pen(); painter.setPen(Qt::darkGray); painter.drawText(Margin, Margin*2 + yPos + textWidth.height() -5, printer.width(), fm.lineSpacing(), Qt::TextExpandTabs | Qt::TextDontClip, ptInfo.storeAddr + ", " +ptInfo.thPhone + ptInfo.storePhone); yPos = yPos + fm.lineSpacing(); // Store Logo painter.drawPixmap(printer.width() - ptInfo.storeLogo.width() - Margin, Margin, ptInfo.storeLogo); // Header line painter.setPen(QPen(Qt::gray, 5, Qt::SolidLine, Qt::FlatCap, Qt::RoundJoin)); painter.drawLine(Margin, 105, printer.width()-Margin, 105); yPos = yPos + 3 * fm.lineSpacing(); // 3times the height of the line // Ticket Number, Date painter.setPen(normalPen); text = ptInfo.thDate; textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText(printer.width()-Margin-textWidth.width(), Margin + yPos +textWidth.height(), text); yPos = yPos + fm.lineSpacing(); // Vendor name, terminal number text = ptInfo.salesPerson + ", " + ptInfo.terminal; textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText(printer.width()-Margin-textWidth.width(), Margin + yPos +textWidth.height(), text); yPos = yPos + 3*fm.lineSpacing(); // Products Subheader int columnQty = 0; if (ptInfo.totDisc <= 0) { columnQty = 90; } int columnPrice= columnQty+100; int columnDisc = columnPrice+100; int columnTotal = 0; if ( ptInfo.totDisc >0 ) columnTotal = columnDisc+100; else columnTotal = columnPrice+100; painter.setPen(Qt::darkBlue); tmpFont = QFont("Bitstream Vera Sans", 10 ); tmpFont.setWeight(QFont::Bold); painter.setFont(tmpFont); painter.drawText(Margin,Margin+yPos, ptInfo.thProduct); text = ptInfo.thQty; painter.drawText(printer.width()/2+columnQty, Margin + yPos, text); text = ptInfo.thPrice; painter.drawText(printer.width()/2+columnPrice, Margin + yPos, text); text = ptInfo.thDiscount; if (ptInfo.totDisc > 0) painter.drawText(printer.width()/2+columnDisc, Margin + yPos, text); text = ptInfo.thTotal; painter.drawText(printer.width()/2+columnTotal, Margin + yPos, text); yPos = yPos + fm.lineSpacing(); painter.setPen(QPen(Qt::darkGray, 1, Qt::SolidLine, Qt::FlatCap, Qt::RoundJoin)); painter.drawLine(Margin, Margin + yPos - 8, printer.width()-Margin, Margin + yPos - 8); painter.setPen(normalPen); painter.setFont(QFont("Bitstream Vera Sans", 10 )); yPos = yPos + fm.lineSpacing(); // End of Header Information. // Content : Each product QLocale localeForPrinting; for (int i = 0; i < ptInfo.ticketInfo.lines.size(); ++i) { //Check if space for the next text line if ( Margin + yPos > printer.height() - Margin ) { printer.newPage(); // no more room on this page yPos = 0; // back to top of page } TicketLineInfo tLine = ptInfo.ticketInfo.lines.at(i); QString idesc = tLine.desc; QString iprice = localeForPrinting.toString(tLine.price,'f',2); QString iqty = localeForPrinting.toString(tLine.qty, 'f', 2); // We must be aware of the locale. europe uses ',' instead of '.' as the decimals separator. if (iqty.endsWith(".00") || iqty.endsWith(",00")) { iqty.chop(3); iqty += " ";}//we chop the trailing zeroes... iqty = iqty+" "+tLine.unitStr; QString idiscount = localeForPrinting.toString(-(tLine.qty*tLine.disc),'f',2); if (tLine.disc <= 0) idiscount = ""; // dont print 0.0 QString idue = localeForPrinting.toString(tLine.total,'f',2); if ( ptInfo.totDisc > 0 ) while (fm.size(Qt::TextExpandTabs | Qt::TextDontClip, idesc).width() >= ((printer.width()/2)-Margin-40)) { idesc.chop(2); } else while (fm.size(Qt::TextExpandTabs | Qt::TextDontClip, idesc).width() >= ((printer.width()/2)-Margin-40+90)) { idesc.chop(2); } painter.drawText(Margin, Margin+yPos, idesc); //first product description... text = iqty; painter.drawText(printer.width()/2+columnQty, Margin+yPos, text); text = iprice; painter.drawText(printer.width()/2+columnPrice, Margin+yPos, text); if ( ptInfo.totDisc > 0 ) { text = idiscount; if (text == "0.0") text = ""; //dont print a 0.0 !!! painter.drawText(printer.width()/2+columnDisc, Margin+yPos, text); } text = idue; painter.drawText(printer.width()/2+columnTotal, Margin+yPos, text); yPos = yPos + fm.lineSpacing(); } //for each item //now the totals... //Check if space for the next text 3 lines if ( (Margin + yPos +fm.lineSpacing()*3) > printer.height() - Margin ) { printer.newPage(); // no more room on this page yPos = 0; // back to top of page } painter.setPen(QPen(Qt::darkGray, 1, Qt::SolidLine, Qt::FlatCap, Qt::RoundJoin)); painter.drawLine(Margin, Margin + yPos - 8, printer.width()-Margin, Margin + yPos - 8); painter.setPen(normalPen); painter.setFont(tmpFont); yPos = yPos + fm.lineSpacing(); if ( ptInfo.totDisc >0 ) painter.drawText((printer.width()/2)+columnDisc, Margin + yPos , ptInfo.tDisc); painter.drawText((printer.width()/2)+columnQty, Margin + yPos , ptInfo.thArticles); painter.drawText((printer.width()/2)+columnTotal, Margin+yPos, ptInfo.thTotals); yPos = yPos + fm.lineSpacing(); // NOTE: I think its redundant to say again the savings. //if (tDisc > 0) { // painter.drawText(Margin, Margin + yPos , line = i18n("You saved %1", KGlobal::locale()->formatMoney(tDisc, QString(), 2));); // yPos = yPos + fm.lineSpacing(); //} //if space, the ticket message. if ( (Margin + yPos +fm.lineSpacing()*4) <= printer.height() - Margin ) { tmpFont = QFont("Bitstream Vera Sans", 12); tmpFont.setItalic(true); painter.setPen(Qt::darkGreen); painter.setFont(tmpFont); yPos = yPos + fm.lineSpacing()*4; painter.drawText((printer.width()/2)-(fm.size(Qt::TextExpandTabs | Qt::TextDontClip, ptInfo.ticketMsg).width()/2)-Margin, Margin+yPos, ptInfo.ticketMsg); } result = painter.end();// this makes the print job start return result; } bool PrintCUPS::printBigEndOfDay(const PrintEndOfDayInfo &pdInfo, QPrinter &printer) { bool result = false; QFont header = QFont("Impact", 25); const int Margin = 20; int yPos = 0; QPainter painter; painter.begin( &printer ); QFontMetrics fm = painter.fontMetrics(); //NOTE from Qt for the drawText: The y-position is used as the baseline of the font QFont tmpFont = QFont("Bitstream Vera Sans", 14); QPen normalPen = painter.pen(); QString text; QSize textWidth; if (pdInfo.logoOnTop) { // Store Logo painter.drawPixmap(printer.width()/2 - (pdInfo.storeLogo.width()/2), Margin, pdInfo.storeLogo); yPos = yPos + pdInfo.storeLogo.height(); // Store Name painter.setFont(header); text = pdInfo.storeName; fm = painter.fontMetrics(); textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText((printer.width()/2)-(textWidth.width()/2),yPos+Margin+textWidth.height(), text); yPos = yPos + textWidth.height()+5; tmpFont = QFont("Bitstream Vera Sans", 14); tmpFont.setItalic(true); painter.setFont(tmpFont); painter.setPen(Qt::darkGray); text = pdInfo.storeAddr; fm = painter.fontMetrics(); textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText((printer.width()/2)-(textWidth.width()/2),yPos+Margin+textWidth.height(), text); yPos = yPos + textWidth.height()+20; } else { // Store Logo painter.drawPixmap(printer.width() - pdInfo.storeLogo.width() - Margin, Margin+20, pdInfo.storeLogo); // Store Name painter.setFont(header); text = pdInfo.storeName; fm = painter.fontMetrics(); textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText(Margin,Margin+textWidth.height(), text); yPos = yPos + textWidth.height()+5; tmpFont = QFont("Bitstream Vera Sans", 14); tmpFont.setItalic(true); painter.setFont(tmpFont); painter.setPen(Qt::darkGray); text = pdInfo.storeAddr; fm = painter.fontMetrics(); textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText(Margin,yPos+Margin+textWidth.height(), text); yPos = yPos + fm.lineSpacing()+20; } // Header line painter.setPen(QPen(Qt::gray, 5, Qt::SolidLine, Qt::FlatCap, Qt::RoundJoin)); painter.drawLine(Margin, Margin+yPos, printer.width()-Margin, Margin+yPos); tmpFont = QFont("Bitstream Vera Sans", 18); tmpFont.setItalic(true); painter.setFont(tmpFont); fm = painter.fontMetrics(); //title text = pdInfo.thTitle; textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText((printer.width()/2)-(textWidth.width()/2), Margin + yPos +textWidth.height()+15, text); yPos = yPos + 2*fm.lineSpacing(); //Date tmpFont = QFont("Bitstream Vera Sans", 13); painter.setFont(tmpFont); painter.setPen(normalPen); fm = painter.fontMetrics(); yPos = yPos + fm.lineSpacing(); text = pdInfo.thDate; textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText((printer.width()/2)-(textWidth.width()/2), Margin + yPos +textWidth.height(), text); yPos = yPos + fm.lineSpacing(); text = pdInfo.salesPerson +" "+ pdInfo.terminal; textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText((printer.width()/2)-(textWidth.width()/2), Margin + yPos +textWidth.height(), text); yPos = yPos + 2*fm.lineSpacing(); // Transaction Headers tmpFont = QFont("Bitstream Vera Sans", 10); painter.setPen(QPen(Qt::blue, 5, Qt::SolidLine, Qt::FlatCap, Qt::RoundJoin)); tmpFont.setBold(true); painter.setFont(tmpFont); fm = painter.fontMetrics(); text = pdInfo.thTicket; textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText(Margin+30, Margin + yPos +textWidth.height(), text); text = pdInfo.thTime; textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText(Margin+130, Margin + yPos +textWidth.height(), text); text = pdInfo.thAmount; textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText(Margin+220, Margin + yPos +textWidth.height(), text); text = pdInfo.thProfit; textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText(Margin+450, Margin + yPos +textWidth.height(), text); text = pdInfo.thPayMethod; textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText(printer.width()-textWidth.width()-Margin, Margin + yPos +textWidth.height(), text); yPos = yPos + 2*fm.lineSpacing(); painter.setPen(QPen(Qt::darkGray, 1, Qt::SolidLine, Qt::FlatCap, Qt::RoundJoin)); painter.drawLine(Margin, Margin + yPos - 8, printer.width()-Margin, Margin + yPos - 8); painter.setPen(normalPen); //TRANSACTION DETAILS tmpFont.setBold(false); painter.setFont(tmpFont); fm = painter.fontMetrics(); painter.setPen(QPen(normalPen)); yPos = yPos + fm.lineSpacing(); //Iterating each transaction foreach(QString trStr, pdInfo.trLines) { QStringList data = trStr.split("|"); if ( (Margin + yPos +fm.lineSpacing()) > printer.height() - Margin ) { printer.newPage(); // no more room on this page yPos = 0; // back to top of page } //we have 5 fields in the string [ORDER] ID, HOUR, AMOUNT, PROFIT, PAYMETHOD text = data.at(0); // ID textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText(Margin+10, Margin + yPos +textWidth.height(), text); text = data.at(1); // HOUR textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText(Margin+130, Margin + yPos +textWidth.height(), text); text = data.at(2); // AMOUNT textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText(Margin+220, Margin + yPos +textWidth.height(), text); text = data.at(3); // PROFIT textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText(Margin+450, Margin + yPos +textWidth.height(), text); text = data.at(4); // PAYMENT METHOD textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText(printer.width()-textWidth.width()-Margin, Margin + yPos +textWidth.height(), text); yPos = yPos + fm.lineSpacing(); } yPos = yPos + fm.lineSpacing(); painter.setPen(QPen(Qt::darkGray, 1, Qt::SolidLine, Qt::FlatCap, Qt::RoundJoin)); painter.drawLine(Margin, Margin + yPos - 8, printer.width()-Margin, Margin + yPos - 8); if ( (Margin + yPos +fm.lineSpacing()) > printer.height() - Margin ) { printer.newPage(); // no more room on this page yPos = 0; // back to top of page } //TOTALS tmpFont.setBold(true); tmpFont.setItalic(true); painter.setFont(tmpFont); painter.setPen(QPen(Qt::black, 5, Qt::SolidLine, Qt::FlatCap, Qt::RoundJoin)); yPos = yPos + fm.lineSpacing(); text = QString::number(pdInfo.trLines.count()); //transaction count painter.drawText(Margin+10, Margin + yPos , text); text = pdInfo.thTotalSales; // sales painter.drawText(Margin+210, Margin + yPos , text); text = pdInfo.thTotalProfit; // profit painter.drawText(Margin+440, Margin + yPos , text); result = painter.end(); return result; } bool PrintCUPS::printSmallEndOfDay(const PrintEndOfDayInfo &pdInfo, QPrinter &printer) { bool result = false; int headerSize = 15; int textSize = 7; if (printer.widthMM() > 150) printer.setPaperSize(QSizeF(104,110), QPrinter::Millimeter); // Resetting to 104mm (4 inches) paper. //When i press "Properties" button on print dialog (qt/cups), and i cancel the dialog, then the size is set to 210mm.. i dont know why. // 210 mm is the size of A4 paper (209.90mm), which it seems to be the default size.. // It is curious that when selecting custom size, the edit boxes for entering size are disabled and with a default 0x0 size.. why? This causes error on printing. CUPS or qt guilty? qDebug()<<"Paper Width: "<<printer.widthMM()<<"mm"<<"; Page Width: "<<printer.width()<<"; calculated headerSize: "<<headerSize<<" Text Size:"<<textSize; QFont header = QFont("Impact", headerSize); const int Margin = printer.width()/40; int yPos = 0; QPainter painter; painter.begin( &printer ); QFontMetrics fm = painter.fontMetrics(); //NOTE from Qt for the drawText: The y-position is used as the baseline of the font QFont tmpFont = QFont("Bitstream Vera Sans", textSize); QPen normalPen = painter.pen(); QString text; QSize textWidth; if (pdInfo.logoOnTop) { // Store Logo QPixmap logo = pdInfo.storeLogo; if (pdInfo.storeLogo.width() > printer.width() ) logo = logo.scaledToWidth( printer.width() ); //scale to the size of the page. painter.drawPixmap(printer.width()/2 - (logo.width()/2), Margin, logo); yPos = yPos + logo.height(); // Store Name painter.setFont(header); text = pdInfo.storeName; fm = painter.fontMetrics(); textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); yPos = yPos + Margin + textWidth.height(); painter.drawText((printer.width()/2)-(textWidth.width()/2),yPos, text); tmpFont = QFont("Bitstream Vera Sans", textSize); tmpFont.setItalic(true); painter.setFont(tmpFont); fm = painter.fontMetrics(); text = pdInfo.storeAddr; textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); yPos = yPos + fm.lineSpacing(); painter.drawText((printer.width()/2)-(textWidth.width()/2), yPos, text); yPos = yPos + fm.lineSpacing()*2; } else { // Store Logo QPixmap logo = pdInfo.storeLogo; if (pdInfo.storeLogo.width() > printer.width()/2 ) logo = logo.scaledToWidth( printer.width()/2 ); //scale to half the size of the page. painter.drawPixmap(printer.width() - logo.width() - Margin, Margin*1.75, logo); // Store Name painter.setFont(header); text = pdInfo.storeName; fm = painter.fontMetrics(); textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText(Margin,Margin+textWidth.height(), text); // Store Address tmpFont = QFont("Bitstream Vera Sans", textSize); tmpFont.setItalic(true); painter.setFont(tmpFont); fm = painter.fontMetrics(); yPos = yPos + fm.lineSpacing()+(Margin*0.75); text = pdInfo.storeAddr; textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.setPen(Qt::darkGray); painter.drawText(Margin, yPos, text); yPos = yPos + fm.lineSpacing()*2; } //FIXME: Check for logo printing!!!! if no logo, text is missplaced... if (pdInfo.storeLogo.isNull()) yPos = yPos + Margin + fm.lineSpacing(); painter.setFont(header); fm = painter.fontMetrics(); //title text = pdInfo.thTitle; textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText((printer.width()/2)-(textWidth.width()/2), yPos, text); //Date painter.setFont(tmpFont); painter.setPen(normalPen); fm = painter.fontMetrics(); yPos = yPos + 2*fm.lineSpacing(); text = pdInfo.thDate; textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText((printer.width()/2)-(textWidth.width()/2), yPos, text); yPos = yPos + fm.lineSpacing(); text = pdInfo.salesPerson +" "+ pdInfo.terminal; textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText((printer.width()/2)-(textWidth.width()/2), yPos, text); yPos = yPos + fm.lineSpacing()*2; int tmpOffset = (printer.width()/5); // Transaction Headers tmpFont.setBold(true); painter.setFont(tmpFont); fm = painter.fontMetrics(); text = pdInfo.thTicket; textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText(Margin, yPos, text); text = pdInfo.thTime; textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText(tmpOffset, yPos, text); text = pdInfo.thAmount; textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText((tmpOffset*2)-Margin*2, yPos, text); text = pdInfo.thProfit; textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText((tmpOffset*3), yPos, text); //text = pdInfo.thPayMethod; //textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); //painter.drawText(tmpOffset*4, yPos, text);//printer.width()-textWidth.width()-Margin, Margin + yPos +textWidth.height(), text); yPos = yPos + fm.lineSpacing(); painter.setPen(QPen(Qt::darkGray, 1, Qt::SolidLine, Qt::FlatCap, Qt::RoundJoin)); painter.drawLine(Margin, yPos, printer.width()-Margin, yPos); painter.setPen(normalPen); //TRANSACTION DETAILS tmpFont.setBold(false); painter.setFont(tmpFont); fm = painter.fontMetrics(); painter.setPen(QPen(normalPen)); yPos = yPos + fm.lineSpacing(); //Iterating each transaction foreach(QString trStr, pdInfo.trLines) { QStringList data = trStr.split("|"); //we have 5 fields in the string [ORDER] ID, HOUR, AMOUNT, PROFIT, PAYMETHOD text = data.at(0); // ID textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText(Margin, yPos, text); text = data.at(1); // HOUR textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText(tmpOffset, yPos, text); text = data.at(2); // AMOUNT textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText((tmpOffset*2)-Margin*2, yPos, text); text = data.at(3); // PROFIT textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText(tmpOffset*3, yPos, text); text = data.at(4); // PAYMENT METHOD textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText(printer.width()-Margin-textWidth.width(), yPos, text); yPos = yPos + fm.lineSpacing(); } yPos = yPos + fm.lineSpacing(); painter.drawLine(Margin, yPos, printer.width()-Margin, yPos); //TOTALS tmpFont.setBold(true); tmpFont.setItalic(true); painter.setFont(tmpFont); yPos = yPos + fm.lineSpacing(); text = QString::number(pdInfo.trLines.count()); //transaction count painter.drawText(Margin, yPos , text); text = pdInfo.thTotalSales; // sales painter.drawText((tmpOffset*2)-Margin*2, yPos , text); text = pdInfo.thTotalProfit; // profit painter.drawText(tmpOffset*3, yPos , text); //print taxes for all sales yPos = yPos + fm.lineSpacing()*2; QStringList tL = pdInfo.thTotalTaxes.split(':'); text = tL.first(); painter.drawText(Margin, yPos , text); yPos = yPos + fm.lineSpacing(); text = tL.last(); painter.drawText(Margin, yPos , text); result = painter.end(); return result; } bool PrintCUPS::printSmallLowStockReport(const PrintLowStockInfo &plInfo, QPrinter &printer) { bool result = false; // calculate font size int headerSize = printer.width()/16; //divisor found by trying, maybe has to do with font metrics? int textSize = headerSize/2; //i think the half of header size is ok qDebug()<<"Paper Size: "<<printer.widthMM()<<"mm x "<<printer.heightMM()<<" -- calculated headerSize: "<<headerSize; QFont header = QFont("Impact", headerSize); const int Margin = printer.width()/40; int yPos = 0; QPainter painter; painter.begin( &printer ); QFontMetrics fm = painter.fontMetrics(); //NOTE from Qt for the drawText: The y-position is used as the baseline of the font QFont tmpFont = QFont("Bitstream Vera Sans", textSize); QPen normalPen = painter.pen(); QString text; QSize textWidth; if (plInfo.logoOnTop) { // Store Logo QPixmap logo = plInfo.storeLogo; if (plInfo.storeLogo.width() > printer.width() ) logo = logo.scaledToWidth( printer.width() ); //scale to half the size of the page. painter.drawPixmap(printer.width()/2 - (logo.width()/2), Margin, logo); yPos = yPos + logo.height(); // Store Name painter.setFont(header); text = plInfo.storeName; fm = painter.fontMetrics(); textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); yPos = yPos + Margin + textWidth.height(); painter.drawText((printer.width()/2)-(textWidth.width()/2),yPos, text); tmpFont.setItalic(true); painter.setFont(tmpFont); fm = painter.fontMetrics(); text = plInfo.storeAddr; textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); yPos = yPos + fm.lineSpacing(); painter.drawText((printer.width()/2)-(textWidth.width()/2), yPos, text); yPos = yPos + fm.lineSpacing()*2; } else { // Store Logo QPixmap logo = plInfo.storeLogo; if (plInfo.storeLogo.width() > printer.width()/2 ) logo = logo.scaledToWidth( printer.width()/2 ); //scale to half the size of the page. painter.drawPixmap(printer.width() - logo.width() - Margin, Margin*1.75, logo); // Store Name painter.setFont(header); text = plInfo.storeName; fm = painter.fontMetrics(); textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText(Margin,Margin+textWidth.height(), text); // Store Address tmpFont.setItalic(true); painter.setFont(tmpFont); fm = painter.fontMetrics(); yPos = yPos + fm.lineSpacing()+(Margin*0.75); text = plInfo.storeAddr; textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.setPen(Qt::darkGray); painter.drawText(Margin, yPos, text); yPos = yPos + fm.lineSpacing()*2; } //FIXME: Check for logo printing!!!! if no logo, text is missplaced... if (plInfo.storeLogo.isNull()) yPos = yPos + Margin + fm.lineSpacing(); // Header line //painter.drawLine(Margin, yPos, printer.width()-Margin, yPos); tmpFont = QFont("Bitstream Vera Sans", textSize+2); tmpFont.setItalic(true); painter.setFont(tmpFont); fm = painter.fontMetrics(); //title text = plInfo.hTitle; textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText((printer.width()/2)-(textWidth.width()/2), yPos, text); yPos = yPos + 2*fm.lineSpacing(); //Date tmpFont = QFont("Bitstream Vera Sans", textSize); painter.setFont(tmpFont); painter.setPen(normalPen); fm = painter.fontMetrics(); yPos = yPos + fm.lineSpacing(); text = plInfo.hDate; textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText((printer.width()/2)-(textWidth.width()/2), yPos, text); yPos = yPos + 2*fm.lineSpacing(); int tmpOffset = printer.width()/3.6; // Content Headers tmpFont = QFont("Bitstream Vera Sans", textSize-2);//NOTE: Making smaller font, its much text on each field to print. tmpFont.setBold(true); painter.setFont(tmpFont); fm = painter.fontMetrics(); //code text = plInfo.hCode; painter.drawText(Margin, yPos, text); //Description text = plInfo.hDesc; while (fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text).width() >= tmpOffset+(tmpOffset*2)+Margin*6) { text.chop(2); } painter.drawText(tmpOffset, yPos, text); //Qty text = plInfo.hQty; //while (fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text).width() >= (tmpOffset*2)+(tmpOffset*3)+Margin*2) { text.chop(2); } painter.drawText((tmpOffset*2)+Margin*7, yPos, text); //SOLD UNITS text = plInfo.hSoldU; //while (fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text).width() >= ((tmpOffset*3)+Margin*2)+tmpOffset*4) { text.chop(2); } painter.drawText((tmpOffset*3)+Margin*2, yPos, text);//printer.width()-Margin-textWidth.width(), yPos, text); yPos = yPos + 2*fm.lineSpacing(); //line painter.drawLine(Margin, yPos, printer.width()-Margin, yPos); //PRODUCTS DETAILS tmpFont.setBold(false); painter.setFont(tmpFont); fm = painter.fontMetrics(); yPos = yPos + fm.lineSpacing(); //Iterating each product //TODO: Maybe, paint a background color in odd rows to make it more readable. foreach(QString trStr, plInfo.pLines) { QStringList data = trStr.split("|"); //we have 5 fields in the string CODE, DESC, STOCK QTY, UNITSTR, SOLDUNITS text = data.at(0); // CODE painter.drawText(Margin, yPos, text); text = data.at(1); // DESCRIPTION while (fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text).width() >= (tmpOffset*2)-Margin*6) { text.chop(2); } painter.drawText(tmpOffset, yPos, text); text = data.at(2); // STOCK QTY // We must be aware of the locale. europe uses ',' instead of '.' as the decimals separator. if (text.endsWith(".00") || text.endsWith(",00")) { text.chop(3); text += " ";}//we chop the trailing zeroes... text = text; //+" "+ data.at(3); // 10 pieces painter.drawText((tmpOffset*2)+Margin*7, yPos, text); text = data.at(4); // SOLD UNITS // We must be aware of the locale. europe uses ',' instead of '.' as the decimals separator. if (text.endsWith(".00") || text.endsWith(",00")) { text.chop(3); text += " ";}//we chop the trailing painter.drawText((tmpOffset*3)+Margin*2, yPos, text);//printer.width()-textWidth.width()-Margin, yPos, text); yPos = yPos + fm.lineSpacing(); } yPos = yPos + fm.lineSpacing(); painter.drawLine(Margin, yPos, printer.width()-Margin, yPos); result = painter.end(); return result; } bool PrintCUPS::printBigLowStockReport(const PrintLowStockInfo &plInfo, QPrinter &printer) { bool result = false; QFont header = QFont("Impact", 25); const int Margin = 20; int yPos = 0; QPainter painter; painter.begin( &printer ); QFontMetrics fm = painter.fontMetrics(); //NOTE from Qt for the drawText: The y-position is used as the baseline of the font QFont tmpFont = QFont("Bitstream Vera Sans", 14); QPen normalPen = painter.pen(); QString text; QSize textWidth; if (plInfo.logoOnTop) { // Store Logo painter.drawPixmap(printer.width()/2 - (plInfo.storeLogo.width()/2), Margin, plInfo.storeLogo); yPos = yPos + plInfo.storeLogo.height(); // Store Name painter.setFont(header); text = plInfo.storeName; fm = painter.fontMetrics(); textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText((printer.width()/2)-(textWidth.width()/2),yPos+Margin+textWidth.height(), text); yPos = yPos + textWidth.height()+5; tmpFont = QFont("Bitstream Vera Sans", 14); tmpFont.setItalic(true); painter.setFont(tmpFont); painter.setPen(Qt::darkGray); text = plInfo.storeAddr; fm = painter.fontMetrics(); textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText((printer.width()/2)-(textWidth.width()/2),yPos+Margin+textWidth.height(), text); yPos = yPos + textWidth.height()+20; } else { // Store Logo painter.drawPixmap(printer.width() - plInfo.storeLogo.width() - Margin, Margin+20, plInfo.storeLogo); // Store Name painter.setFont(header); text = plInfo.storeName; fm = painter.fontMetrics(); textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText(Margin,Margin+textWidth.height(), text); yPos = yPos + textWidth.height()+5; tmpFont = QFont("Bitstream Vera Sans", 14); tmpFont.setItalic(true); painter.setFont(tmpFont); painter.setPen(Qt::darkGray); text = plInfo.storeAddr; fm = painter.fontMetrics(); textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText(Margin,yPos+Margin+textWidth.height(), text); yPos = yPos + fm.lineSpacing()+20; } // Header line painter.setPen(QPen(Qt::gray, 5, Qt::SolidLine, Qt::FlatCap, Qt::RoundJoin)); painter.drawLine(Margin, Margin+yPos, printer.width()-Margin, Margin+yPos); tmpFont = QFont("Bitstream Vera Sans", 18); tmpFont.setItalic(true); painter.setFont(tmpFont); fm = painter.fontMetrics(); //title text = plInfo.hTitle; textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText((printer.width()/2)-(textWidth.width()/2), Margin + yPos +textWidth.height()+15, text); yPos = yPos + 2*fm.lineSpacing(); //Date tmpFont = QFont("Bitstream Vera Sans", 13); painter.setFont(tmpFont); painter.setPen(normalPen); fm = painter.fontMetrics(); yPos = yPos + fm.lineSpacing(); text = plInfo.hDate; textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText((printer.width()/2)-(textWidth.width()/2), Margin + yPos +textWidth.height(), text); yPos = yPos + 2*fm.lineSpacing(); // Content Headers tmpFont = QFont("Bitstream Vera Sans", 10); painter.setPen(QPen(Qt::blue, 5, Qt::SolidLine, Qt::FlatCap, Qt::RoundJoin)); tmpFont.setBold(true); painter.setFont(tmpFont); fm = painter.fontMetrics(); text = plInfo.hCode; textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText(Margin+30, Margin + yPos +textWidth.height(), text); text = plInfo.hDesc; textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText(Margin+160, Margin + yPos +textWidth.height(), text); text = plInfo.hQty; textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText(Margin+450, Margin + yPos +textWidth.height(), text); //text = plInfo.hUnitStr; //textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); //painter.drawText(printer.width()-textWidth.width()-Margin, Margin + yPos +textWidth.height(), text); text = plInfo.hSoldU; textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText(printer.width()-Margin-textWidth.width(), Margin + yPos +textWidth.height(), text); yPos = yPos + 2*fm.lineSpacing(); painter.setPen(QPen(Qt::darkGray, 1, Qt::SolidLine, Qt::FlatCap, Qt::RoundJoin)); painter.drawLine(Margin, Margin + yPos - 8, printer.width()-Margin, Margin + yPos - 8); painter.setPen(normalPen); //PRODUCTS DETAILS tmpFont.setBold(false); painter.setFont(tmpFont); fm = painter.fontMetrics(); painter.setPen(QPen(normalPen)); yPos = yPos + fm.lineSpacing(); //Iterating each product foreach(QString trStr, plInfo.pLines) { if ( Margin + yPos > printer.height() - Margin ) { printer.newPage(); // no more room on this page yPos = 0; // back to top of page } QStringList data = trStr.split("|"); //we have 5 fields in the string CODE, DESC, STOCK QTY, UNITSTR, SOLDUNITS text = data.at(0); // CODE textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText(Margin+10, Margin + yPos +textWidth.height(), text); text = data.at(1); // DESCRIPTION while (fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text).width() >= 270) { text.chop(2); } textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText(Margin+160, Margin + yPos +textWidth.height(), text); text = data.at(2); // STOCK QTY // We must be aware of the locale. europe uses ',' instead of '.' as the decimals separator. if (text.endsWith(".00") || text.endsWith(",00")) { text.chop(3); text += " ";}//we chop the trailing zeroes... text = text +" "+ data.at(3); // 10 pieces textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText(Margin+450, Margin + yPos +textWidth.height(), text); text = data.at(4); // SOLD UNITS // We must be aware of the locale. europe uses ',' instead of '.' as the decimals separator. if (text.endsWith(".00") || text.endsWith(",00")) { text.chop(3); text += " ";}//we chop the trailing textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText(printer.width()-textWidth.width()-Margin, Margin + yPos +textWidth.height(), text); yPos = yPos + fm.lineSpacing(); } yPos = yPos + fm.lineSpacing(); painter.setPen(QPen(Qt::darkGray, 1, Qt::SolidLine, Qt::FlatCap, Qt::RoundJoin)); painter.drawLine(Margin, Margin + yPos - 8, printer.width()-Margin, Margin + yPos - 8); result = painter.end(); return result; } bool PrintCUPS::printSmallSOTicket(const PrintTicketInfo &ptInfo, QPrinter &printer) { bool result = false; // calculate font size const int headerSize = printer.width()/16; //divisor found by trying, maybe has to do with font metrics? const int textSize = headerSize/2; //i think the half of header size is ok qDebug()<<"Paper Width: "<<printer.widthMM()<<"mm"<<"; Page Width: "<<printer.width()<<"; calculated headerSize: "<<headerSize; QFont header = QFont("Impact", headerSize); const int Margin = printer.width()/40; int yPos = 0; QPainter painter; painter.begin( &printer ); QFontMetrics fm = painter.fontMetrics(); //NOTE from Qt for the drawText: The y-position is used as the baseline of the font // Header QFont tmpFont = QFont("Bitstream Vera Sans", textSize); QPen normalPen = painter.pen(); QString text; QSize textWidth; // Store Name painter.setFont(header); yPos = Margin + painter.fontMetrics().height(); painter.setFont(header); fm = painter.fontMetrics(); text = ptInfo.storeName; textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText((printer.width()/2)-(textWidth.width()/2),yPos, text); tmpFont.setItalic(false); painter.setFont(tmpFont); fm = painter.fontMetrics(); yPos = yPos + fm.lineSpacing()*2; //Date, Ticket number painter.setPen(normalPen); text = ptInfo.thDate ; textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText(Margin, yPos, text); //change font for ticket number... bigger. Check for really big numbers to fit the page. tmpFont = QFont("Bitstream Vera Sans", textSize+3); tmpFont.setItalic(false); tmpFont.setBold(true); painter.setFont(tmpFont); fm = painter.fontMetrics(); text = ptInfo.thTicket; textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText(printer.width() - textWidth.width() - Margin, yPos, text); //change font again tmpFont = QFont("Bitstream Vera Sans", textSize); tmpFont.setItalic(false); tmpFont.setBold(false); painter.setFont(tmpFont); fm = painter.fontMetrics(); yPos = yPos + fm.lineSpacing(); //Vendor, terminal number text = ptInfo.salesPerson + ", " + ptInfo.terminal; textWidth = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text); painter.drawText(Margin, yPos, text); yPos = yPos + 3*fm.lineSpacing(); // Products Subheader int offsetQty = printer.width()/5; tmpFont.setWeight(QFont::Bold); painter.setFont(tmpFont); fm = painter.fontMetrics(); text = ptInfo.thProduct; while (fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text).width() >= offsetQty*4 ) { text.chop(2); } painter.drawText(Margin,yPos, text); text = ptInfo.thQty; painter.drawText(offsetQty*4, yPos, text); yPos = yPos + fm.lineSpacing(); painter.drawLine(Margin, yPos, printer.width()-Margin, yPos); painter.setPen(normalPen); tmpFont = QFont("Bitstream Vera Sans", textSize ); painter.setFont(tmpFont); yPos = yPos + fm.lineSpacing(); // End of Header Information. // Content : Each product QLocale localeForPrinting; for (int i = 0; i < ptInfo.ticketInfo.lines.size(); ++i) { TicketLineInfo tLine = ptInfo.ticketInfo.lines.at(i); QString idesc = tLine.desc; QString iqty = localeForPrinting.toString(tLine.qty, 'f', 2); bool isGroup = ptInfo.ticketInfo.lines.at(i).isGroup; QString sp; QDateTime deliveryDT = ptInfo.ticketInfo.lines.at(i).deliveryDateTime; // We must be aware of the locale. europe uses ',' instead of '.' as the decimals separator. // note: QLocale has a method that does this locale aware! if the locale is set correctly if (iqty.endsWith(".00") || iqty.endsWith(",00")) { iqty.chop(3); iqty += " ";}//we chop the trailing zeroes... iqty = iqty; tmpFont.setBold(true); painter.setFont(tmpFont); fm = painter.fontMetrics(); text = idesc; while (fm.size(Qt::TextExpandTabs | Qt::TextDontClip, text).width() >= offsetQty*2 ) { text.chop(2); } painter.drawText(Margin, yPos, text); //first product description... text = iqty; tmpFont.setBold(false); painter.setFont(tmpFont); fm = painter.fontMetrics(); painter.drawText(offsetQty*4, yPos, text); yPos = yPos + fm.lineSpacing(); //check if there is a Special Order, to print contents if ( !tLine.geForPrint.isEmpty() ) { //QStringList strList = tLine.geForPrint.split("|"); //strList.removeFirst(); QStringList tmpList = tLine.geForPrint.split("|"); QStringList strList; tmpList.removeFirst(); //check text lenght double maxL = ((printer.width())-Margin*2); foreach(QString strTmp, tmpList) { fm = painter.fontMetrics(); QString strCopy = strTmp; double realTrozos = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, strTmp).width() / maxL; int trozos = realTrozos; double diff = (realTrozos - trozos); if (diff > 0.25 && trozos > 0) trozos += 1; int tamTrozo = 0; if (trozos > 0) { tamTrozo = (strTmp.length()/trozos); } else { tamTrozo = strTmp.length(); } QStringList otherList; for (int x = 1; x <= trozos; x++) { //we repeat for each trozo if (x*(tamTrozo-1) < strCopy.length()) strCopy.insert(x*(tamTrozo-1), "| "); //create a section otherList = strCopy.split("|"); } if (!otherList.isEmpty()) strList << otherList; if (trozos < 1) strList << strTmp; //qDebug()<<"Trozos:"<<trozos<<" tamTrozo:"<<tamTrozo<<" realTrozos:"<<QString::number(realTrozos,'f', 2)<<" maxL:"<<maxL<<" strTmp.width in pixels:"<<fm.size(Qt::TextExpandTabs | Qt::TextDontClip, strTmp).width()<<" diff:"<<diff; } foreach(QString str/*Tmp*/, strList) { painter.drawText(Margin, yPos, str/*Tmp*/); yPos = yPos + fm.lineSpacing(); } ///Check for delivery date and if its a SO if (!isGroup && tLine.payment>0 ) { sp = ptInfo.deliveryDateStr + deliveryDT.toString(" ddd d MMMM, h:m ap"); //TODO FIXME:hey i18n stuff!!! tmpFont.setBold(true); painter.setFont(tmpFont); fm = painter.fontMetrics(); painter.drawText(Margin, yPos, sp); yPos = yPos + fm.lineSpacing(); tmpFont.setBold(false); painter.setFont(tmpFont); fm = painter.fontMetrics(); yPos = yPos + fm.lineSpacing(); } yPos = yPos + fm.lineSpacing(); } } //for each item painter.drawLine(Margin, yPos, printer.width()-Margin, yPos); result = painter.end();// this makes the print job start return result; }
88,873
C++
.cpp
1,825
43.783014
243
0.669212
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
752,791
azahar.cpp
hiramvillarreal_iotpos/dataAccess/azahar.cpp
/************************************************************************** * Copyright © 2007-2012 by Miguel Chavez Gamboa * * hiramvillarreal.ap@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include <QWidget> #include <QByteArray> #include "azahar.h" #include <klocale.h> Azahar::Azahar(QWidget * parent): QObject(parent) { errorStr = ""; m_mainClient = "undefined"; } Azahar::~Azahar() { //qDebug()<<"*** AZAHAR DESTROYED ***"; } void Azahar::initDatabase(QString user, QString server, QString password, QString dbname) { QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8")); db = QSqlDatabase::addDatabase("QMYSQL"); db.setHostName(server); db.setDatabaseName(dbname); db.setUserName(user); db.setPassword(password); if (!db.isOpen()) db.open(); if (!db.isOpen()) db.open(); } void Azahar::setDatabase(const QSqlDatabase& database) { db = database; if (!db.isOpen()) db.open(); } bool Azahar::isConnected() { return db.isOpen(); } void Azahar::setError(QString err) { errorStr = err; } QString Azahar::lastError() { return errorStr; } bool Azahar::correctStock(qulonglong pcode, double oldStockQty, double newStockQty, const QString &reason ) { //each correction is an insert to the table. bool result1, result2; result1 = result2 = false; if (!db.isOpen()) db.open(); //Check if the desired product is a a group. Or hasUnlimitedStock ProductInfo p = getProductInfo(QString::number(pcode)); if ( p.isAGroup || p.hasUnlimitedStock ) return false; QSqlQuery query(db); QDate date = QDate::currentDate(); QTime time = QTime::currentTime(); query.prepare("INSERT INTO stock_corrections (product_id, new_stock_qty, old_stock_qty, reason, date, time) VALUES(:pcode, :newstock, :oldstock, :reason, :date, :time); "); query.bindValue(":pcode", pcode); query.bindValue(":newstock", newStockQty); query.bindValue(":oldstock", oldStockQty); query.bindValue(":reason", reason); query.bindValue(":date", date.toString("yyyy-MM-dd")); query.bindValue(":time", time.toString("hh:mm")); if (!query.exec()) setError(query.lastError().text()); else result1=true; //modify stock QSqlQuery query2(db); query2.prepare("UPDATE products set stockqty=:newstock where code=:pcode;"); query2.bindValue(":pcode", pcode); query2.bindValue(":newstock", newStockQty); if (!query2.exec()) setError(query2.lastError().text()); else result2=true; return (result1 && result2); } double Azahar::getProductStockQty(qulonglong code) { double result=0.0; if (db.isOpen()) { QString qry = QString("SELECT stockqty from products WHERE code=%1").arg(code); QSqlQuery query(db); if (!query.exec(qry)) { int errNum = query.lastError().number(); QSqlError::ErrorType errType = query.lastError().type(); QString error = query.lastError().text(); QString details = i18n("Error #%1, Type:%2\n'%3'",QString::number(errNum), QString::number(errType),error); } if (query.size() <= 0) setError(i18n("Error serching product id %1, Rows affected: %2", code,query.size())); else { while (query.next()) { int fieldStock = query.record().indexOf("stockqty"); int fieldIsUnlimited = query.record().indexOf("hasUnlimitedStock"); result = query.value(fieldStock).toDouble(); //return stock if ( query.value(fieldIsUnlimited).toBool() ) result = 999999; //just make sure we do not return 0 for unlimited stock items. } } } return result; } qulonglong Azahar::getProductOfferCode(qulonglong code) { qulonglong result=0; if (db.isOpen()) { QString qry = QString("SELECT id,product_id from offers WHERE product_id=%1").arg(code); QSqlQuery query(db); if (!query.exec(qry)) { int errNum = query.lastError().number(); QSqlError::ErrorType errType = query.lastError().type(); QString error = query.lastError().text(); QString details = i18n("Error #%1, Type:%2\n'%3'",QString::number(errNum), QString::number(errType),error); } if (query.size() <= 0) setError(i18n("Error serching offer id %1, Rows affected: %2", code,query.size())); else { while (query.next()) { int fieldId = query.record().indexOf("id"); result = query.value(fieldId).toULongLong(); //return offer id } } } return result; } qulonglong Azahar::getNextProductCode() { qulonglong r = 0; if (!db.isOpen()) db.open(); QSqlQuery myQuery(db); QString qry("SELECT * FROM products ORDER BY code DESC LIMIT 1;"); if (myQuery.exec(qry) ) { while (myQuery.next()) { int numId = myQuery.record().indexOf("code"); r = myQuery.value(numId).toULongLong(); } } return r; } ProductInfo Azahar::getProductInfo(const QString &code, const bool &notConsiderDiscounts) { ProductInfo info; info.code=0; info.desc="Ninguno"; info.price=0; info.disc=0; info.cost=0; info.lastProviderId = 0; info.department=0; info.category=0; info.subcategory=0; info.taxmodelid=0; //for future use! MCH DEC 28 2010 info.units=0; info.points=0; info.row=-1;info.qtyOnList=-1;info.purchaseQty=-1; info.discpercentage=0; info.validDiscount=false; info.alphaCode = "-NA-"; info.vendorCode = "-NA-"; info.lastProviderId = 0; info.isAGroup = false; info.isARawProduct = false; info.groupPriceDrop = 0; info.hasUnlimitedStock = false; info.isNotDiscountable = false; info.subcategory = 0; QString rawCondition; if (!db.isOpen()) db.open(); if (db.isOpen()) { QString qry = QString("SELECT P.code as CODE, \ P.alphacode as ALPHACODE, \ P.vendorcode as VENDORCODE, \ P.name as NAME ,\ P.price as PRICE, \ P.cost as COST ,\ P.stockqty as STOCKQTY, \ P.units as UNITS, \ P.points as POINTS, \ P.photo as PHOTO, \ P.department as DEPARTMENTID, \ P.category as CATID, \ P.subcategory as SUBCATID, \ P.lastproviderid as PROVIDERID, \ P.taxpercentage as TAX1, \ P.extrataxes as TAX2, \ P.taxmodel as TAXMODELID, \ P.isARawProduct as ISRAW, \ P.isAGroup as ISGROUP, \ P.groupElements as GE, \ P.groupPriceDrop as GPRICEDROP,\ P.soldunits as SOLDUNITS, \ P.isNotDiscountable as NONDISCOUNT, \ P.hasUnlimitedStock as UNLIMITEDSTOCK, \ U.text as UNITSDESC, \ C.text as CATEGORY, \ PR.name as LASTPROVIDER ,\ T.tname as TAXNAME, \ T.elementsid as TAXELEM \ FROM products AS P, taxmodels as T, providers as PR, categories as C, measures as U \ WHERE PR.id=P.lastproviderid AND T.modelid=P.taxmodel \ AND C.catid=P.category AND U.id=P.units\ AND (CODE='%1' or ALPHACODE='%1');").arg(code); QSqlQuery query(db); if (!query.exec(qry)) { int errNum = query.lastError().number(); QSqlError::ErrorType errType = query.lastError().type(); QString error = query.lastError().text(); QString details = i18n("Error #%1, Type:%2\n'%3'",QString::number(errNum), QString::number(errType),error); setError(i18n("Error getting product information for code %1, Rows affected: %2", code,query.size())); } else { while (query.next()) { int fieldTax1= query.record().indexOf("TAX1"); int fieldTax2= query.record().indexOf("TAX2"); int fieldGroupPD = query.record().indexOf("GPRICEDROP"); int fieldCODE = query.record().indexOf("CODE"); int fieldDesc = query.record().indexOf("NAME"); int fieldPrice= query.record().indexOf("PRICE"); int fieldPhoto= query.record().indexOf("PHOTO"); int fieldCost= query.record().indexOf("COST"); int fieldUnits= query.record().indexOf("UNITS"); int fieldUnitsDESC= query.record().indexOf("UNITSDESC"); //int fieldTaxName= query.record().indexOf("TAXNAME"); int fieldTaxModelId= query.record().indexOf("TAXMODELID"); //int fieldCategoryName= query.record().indexOf("CATEGORY"); int fieldDepartmentId= query.record().indexOf("DEPARTMENTID"); int fieldCategoryId= query.record().indexOf("CATID"); int fieldSubCategoryId= query.record().indexOf("SUBCATID"); int fieldPoints= query.record().indexOf("POINTS"); //int fieldLastProviderName = query.record().indexOf("LASTPROVIDER"); int fieldLastProviderId = query.record().indexOf("PROVIDERID"); int fieldAlphaCode = query.record().indexOf("ALPHACODE"); int fieldVendorCode = query.record().indexOf("VENDORCODE"); int fieldTaxElem = query.record().indexOf("TAXELEM"); int fieldStock= query.record().indexOf("STOCKQTY"); int fieldIsGroup = query.record().indexOf("ISGROUP"); int fieldIsRaw = query.record().indexOf("ISRAW"); int fieldGE = query.record().indexOf("GE"); int fieldSoldU = query.record().indexOf("SOLDUNITS"); int fieldUnlimited = query.record().indexOf("UNLIMITEDSTOCK"); int fieldNonDiscount = query.record().indexOf("NONDISCOUNT"); info.code = query.value(fieldCODE).toULongLong(); info.alphaCode = query.value(fieldAlphaCode).toString(); info.vendorCode = query.value(fieldVendorCode).toString(); info.desc = query.value(fieldDesc).toString(); info.price = query.value(fieldPrice).toDouble(); info.photo = query.value(fieldPhoto).toByteArray(); info.stockqty = query.value(fieldStock).toDouble(); info.cost = query.value(fieldCost).toDouble(); info.tax = query.value(fieldTax1).toDouble(); ///TO be removed later, when taxmodel is coded. info.extratax = query.value(fieldTax2).toDouble(); ///TO be removed later, when taxmodel is coded. info.units = query.value(fieldUnits).toInt(); info.unitStr = query.value(fieldUnitsDESC).toString(); info.department = query.value(fieldDepartmentId).toInt(); info.category = query.value(fieldCategoryId).toInt(); info.subcategory = query.value(fieldSubCategoryId).toInt(); info.utility = info.price - info.cost; info.row = -1; info.points = query.value(fieldPoints).toInt(); info.qtyOnList = -1; info.purchaseQty = -1; info.lastProviderId = query.value(fieldLastProviderId).toULongLong(); info.soldUnits = query.value(fieldSoldU).toDouble(); info.isARawProduct = query.value(fieldIsRaw).toBool(); info.isAGroup = query.value(fieldIsGroup).toBool(); info.groupPriceDrop = query.value(fieldGroupPD).toDouble(); info.taxmodelid = query.value(fieldTaxModelId).toULongLong(); info.taxElements = query.value(fieldTaxElem).toString(); info.groupElementsStr = query.value(fieldGE).toString(); info.hasUnlimitedStock = query.value(fieldUnlimited).toBool(); info.isNotDiscountable = query.value(fieldNonDiscount).toBool(); qDebug()<<info.desc<<" DEP:"<<info.department<<" CAT:"<<info.category<<" SUBCAT:"<<info.subcategory; } if ( info.hasUnlimitedStock ) info.stockqty = 999999; //just make sure we do not return 0 for unlimited stock items. ///NOTE:negative stock will be reported as is (negative), iotpos must verify at settings if allowing negative stock with an alert. /** @TODO: for future releases where taxmodel is included in code //get missing stuff - tax,offers for the requested product if (info.isAGroup) //If its a group, the taxmodel is ignored, the tax will be its elements taxes info.tax = getGroupAverageTax(info.code); ///NOTE: This may be deprecated.. see the getGroupPriceAndTax() method else info.tax = getTotalTaxPercent(info.taxElements); if (getConfigTaxIsIncludedInPrice()) { ///tax is included in price... mexico style. double pWOtax = info.price/(1+((info.tax)/100)); info.totaltax = pWOtax*((info.tax)/100); // in money... } else { ///tax is not included in price... usa style. info.totaltax = info.price*(1+(info.tax/100)); //tax in money } **/ ///NOTE FOR DISCOUNTS: TODO: ADD THIS TO THE USER MANUAL // If a group contains product with discounts THOSE ARE NOT TAKEN INTO CONSIDERATION, // The only DISCOUNT for a GROUP is the DISCOUNT created for the GROUP PRODUCT -not for its contents-. // The discounts for GROUPS are PERPETUAL. // Another way to assign a "discount" for a group is reducing the price in the product editor // this is not considered a discount but a lower price, and both can coexist so /// be CAREFUL with this! //get discount info... if have one. QSqlQuery query2(db); //if ( !info.isNotDiscountable ) { //get discounts if !isNotDiscountable... if (query2.exec(QString("Select * from offers where product_id=%1").arg(info.code) )) { QList<double> descuentos; descuentos.clear(); while (query2.next()) // return the valid discount only (and the greater one if many). { int fieldDisc = query2.record().indexOf("discount"); int fieldDateStart = query2.record().indexOf("datestart"); int fieldDateEnd = query2.record().indexOf("dateend"); double descP= query2.value(fieldDisc).toDouble(); QDate dateStart = query2.value(fieldDateStart).toDate(); QDate dateEnd = query2.value(fieldDateEnd).toDate(); QDate now = QDate::currentDate(); //See if the offer is in a valid range... if (info.isAGroup) { /// if produc is a group, the discount has NO DATE LIMITS!!! its valid forever. descuentos.append(descP); } else if ((dateStart<dateEnd) && (dateStart<=now) && (dateEnd>=now) ) { //save all discounts here and decide later to return the bigger valid discount. descuentos.append(descP); } } //now which is the bigger valid discount? qSort(descuentos.begin(), descuentos.end(), qGreater<int>()); //qDebug()<<"DESCUENTOS ORDENADOS DE MAYOR A MENOR:"<<descuentos; if (!descuentos.isEmpty()) { //get the first item, which is the greater one. info.validDiscount = true; info.discpercentage = descuentos.first(); info.disc = (info.discpercentage/100) * (info.price); //round((info.discpercentage/100) * (info.price*100))/100; //FIXME:This is not necesary VALID. } else {info.disc = 0; info.validDiscount =false;} } //} else {info.disc = 0; info.validDiscount = false;} // if !nondiscountable /// If its a group, calculate the right price first. @note: this will be removed when taxmodels are coded. if (info.isAGroup) { //get each content price and tax percentage. GroupInfo gInfo = getGroupPriceAndTax(info); info.price = gInfo.price; //it includes price drop! info.tax = gInfo.tax; info.extratax = 0; //accumulated in tax... //qDebug()<<"=================== GROUP Price:"<<info.price<<" Tax:"<<info.tax<<"======================"; } ///tax calculation - it depends on discounts... @note: this will be removed when taxmodels are coded. double pWOtax = 0; if (getConfigTaxIsIncludedInPrice()) //added on jan 28 2010. pWOtax= info.price/(1+((info.tax+info.extratax)/100)); else pWOtax = info.price; //take into account the discount. if (info.validDiscount) { double iDisc=0; iDisc = (notConsiderDiscounts) ? 0 : (info.discpercentage/100)*pWOtax; //if (notConsiderDiscounts) qDebug()<<" ================= WARNING: NOT CONSIDERING DISCOUNT FOR TAX CALCULATION! ======================= "; pWOtax = pWOtax - iDisc; } //finally we have on pWOtax the price without tax and discount for 1 item ///NOTE: Aug 17 2011: this tax does not take into account the ocassional discounts or price changes. It may be false. double tax1m = (info.tax/100)*pWOtax; double tax2m = (info.extratax/100)*pWOtax; info.totaltax = tax1m + tax2m; //qDebug()<<" getProductInfo() :: Total tax for product "<<info.desc<<info.tax+info.extratax<< " $:"<<info.totaltax; ///end of tax calculation } } return info; } // QList<ProductInfo> Azahar::getTransactionGroupsList(qulonglong tid) // { // QList<ProductInfo> list; // QStringList groupsList = getTransactionInfo(tid).groups.split(","); // foreach(QString ea, groupsList) { // qulonglong c = ea.section('/',0,0).toULongLong(); // double q = ea.section('/',1,1).toDouble(); // ProductInfo pi = getProductInfo(c); // pi.qtyOnList = q; // list.append(pi); // } // return list; // } qulonglong Azahar::getProductCode(QString text) { QSqlQuery query(db); qulonglong code=0; if (query.exec(QString("select code from products where name='%1';").arg(text))) { while (query.next()) { int fieldId = query.record().indexOf("code"); code = query.value(fieldId).toULongLong(); } } else { //qDebug()<<"ERROR: "<<query.lastError(); setError(query.lastError().text()); } return code; } qulonglong Azahar::getProductCodeFromAlphacode(QString text) { QSqlQuery query(db); qulonglong code=0; if (query.exec(QString("select code from products where alphacode='%1';").arg(text))) { while (query.next()) { int fieldId = query.record().indexOf("code"); code = query.value(fieldId).toULongLong(); } } else { //qDebug()<<"ERROR: "<<query.lastError(); setError(query.lastError().text()); } return code; } qulonglong Azahar::getProductCodeFromVendorcode(QString text) { QSqlQuery query(db); qulonglong code=0; if (query.exec(QString("select code from products where vendorcode='%1';").arg(text))) { while (query.next()) { int fieldId = query.record().indexOf("code"); code = query.value(fieldId).toULongLong(); } } else { //qDebug()<<"ERROR: "<<query.lastError(); setError(query.lastError().text()); } return code; } /// UPDATED: This searches products by description and alphacode. -Dec 28 2011- QList<qulonglong> Azahar::getProductsCode(QString regExpName) { QList<qulonglong> result; result.clear(); QSqlQuery query(db); QString qry; QString tmpQry; if (regExpName == "*") qry = "SELECT code from products;"; else { if ( regExpName.contains(' ') ) { /// bujia' 'platino' 'honda //Podria ser ..WHERE name REGEXP 'bujia|platino|honda'. Pero como es un OR tambien nos regresaria los que contengan al menos uno de ellos. QString tmpS = regExpName; tmpS.replace(' ', "' '"); tmpS = QString("'%1'").arg(tmpS); QStringList list = tmpS.split(' ', QString::SkipEmptyParts, Qt::CaseInsensitive); tmpQry = list.join(" AND `name` REGEXP "); QString tmpQry2 = tmpQry; tmpQry2 = tmpQry2.replace("name", "alphacode"); qry = QString("select code,name,alphacode from products WHERE (`name` REGEXP %1) OR (`alphacode` REGEXP %2) ").arg(tmpQry).arg(tmpQry2); } else qry = QString("select code,name,alphacode from products WHERE `name` REGEXP '%1' OR `alphacode` REGEXP '%1'").arg(regExpName); } qDebug()<<"QUERY:"<<qry; //TODO: When user searches text like "white collar" and there are products like "white and red collar" or "white and brilliant collar" then the products are not found. //The key is to separate words with an OR: ..WHERE name REGEXP 'white' OR name REGEXP 'collar' //see if the regExpName contains spaces if (query.exec(qry)) { while (query.next()) { int fieldId = query.record().indexOf("code"); qulonglong id = query.value(fieldId).toULongLong(); result.append(id); //qDebug()<<"APPENDING TO PRODUCTS LIST:"<<id; } } else { setError(query.lastError().text()); } return result; } QStringList Azahar::getProductsList() { QStringList result; result.clear(); QSqlQuery query(db); if (query.exec("select name from products;")) { while (query.next()) { int fieldText = query.record().indexOf("name"); QString text = query.value(fieldText).toString(); result.append(text); } } else { setError(query.lastError().text()); } return result; } bool Azahar::insertProduct(ProductInfo info) { bool result = false; if (!db.isOpen()) db.open(); QSqlQuery query(db); //some buggy info can cause troubles. bool groupValueOK = false; bool rawValueOK = false; if (info.isAGroup == 0 || info.isAGroup == 1) groupValueOK=true; if (info.isARawProduct == 0 || info.isARawProduct == 1) rawValueOK=true; if (!groupValueOK) info.isAGroup = 0; if (!rawValueOK) info.isARawProduct = 0; info.taxmodelid = 1; ///FIXME: Delete this code when taxmodels are added, for now, insert default one. if (info.hasUnlimitedStock) info.stockqty = 1; //for not showing "Not Available" in the product delegate. query.prepare("INSERT INTO products (code, name, price, stockqty, cost, soldunits, datelastsold, units, taxpercentage, extrataxes, photo, department, category, subcategory, points, alphacode, vendorcode, lastproviderid, isARawProduct,isAGroup, groupElements, groupPriceDrop, taxmodel, hasUnlimitedStock, isNotDiscountable ) VALUES (:code, :name, :price, :stock, :cost, :soldunits, :lastgetld, :units, :tax1, :tax2, :photo, :department, :category, :subcategory, :points, :alphacode, :vendorcode, :lastproviderid, :isARaw, :isAGroup, :groupE, :groupPriceDrop, :taxmodel, :unlimitedStock, :NonDiscountable);"); query.bindValue(":code", info.code); query.bindValue(":name", info.desc); query.bindValue(":price", info.price); query.bindValue(":stock", info.stockqty); query.bindValue(":cost", info.cost); query.bindValue(":soldunits", 0); query.bindValue(":lastsold", "1970-01-01"); query.bindValue(":units", info.units); query.bindValue(":tax1", info.tax); query.bindValue(":tax2", info.extratax); query.bindValue(":photo", info.photo); query.bindValue(":department", info.department); query.bindValue(":category", info.category); query.bindValue(":subcategory", info.subcategory); query.bindValue(":points", info.points); query.bindValue(":alphacode", info.alphaCode); query.bindValue(":vendorcode", info.vendorCode); query.bindValue(":lastproviderid", info.lastProviderId); query.bindValue(":isAGroup", info.isAGroup); query.bindValue(":isARaw", info.isARawProduct); query.bindValue(":groupE", info.groupElementsStr); query.bindValue(":groupPriceDrop", info.groupPriceDrop); query.bindValue(":taxmodel", info.taxmodelid); //for later use query.bindValue(":unlimitedStock", info.hasUnlimitedStock); query.bindValue(":NonDiscountable", info.isNotDiscountable); if (!query.exec()) setError(query.lastError().text()); else result=true; /** @note & TODO: Document this for the user. * If the new product's code is reused, and a discount exists in the offers table, it will be deleted. **/ QSqlQuery queryX(db); if (queryX.exec(QString("Select id from offers where product_id=%1").arg(info.code) )) { while (queryX.next()) { int fieldId = queryX.record().indexOf("id"); qulonglong oId = queryX.value(fieldId).toULongLong(); deleteOffer(oId); qDebug()<<" **WARNING** Deleting Existing Offer for the new Product"; } } return result; } bool Azahar::updateProduct(ProductInfo info, qulonglong oldcode) { bool result = false; if (!db.isOpen()) db.open(); QSqlQuery query(db); //some buggy info can cause troubles. bool groupValueOK = false; bool rawValueOK = false; if (info.isAGroup == 0 || info.isAGroup == 1) groupValueOK=true; if (info.isARawProduct == 0 || info.isARawProduct == 1) rawValueOK=true; if (!groupValueOK) info.isAGroup = 0; if (!rawValueOK) info.isARawProduct = 0; /// TODO FIXME: Remove the next line when taxmodels are implemented info.taxmodelid = 1; if (info.hasUnlimitedStock) info.stockqty = 1; //for not showing "Not Available" in the product delegate. //query.prepare("UPDATE products SET code=:newcode, photo=:photo, name=:name, price=:price, stockqty=:stock, cost=:cost, units=:measure, taxpercentage=:tax1, extrataxes=:tax2, category=:category, points=:points, alphacode=:alphacode, lastproviderid=:lastproviderid , isARawProduct=:isRaw, isAGroup=:isGroup, groupElements=:ge, groupPriceDrop=:groupPriceDrop WHERE code=:id"); ///TODO: remove the taxpercentage and extrataxes when taxmodel is implemented query.prepare("UPDATE products SET \ code=:newcode, \ name=:name, \ price=:price, \ cost=:cost, \ stockqty=:stock, \ units=:measure, \ taxpercentage=:tax1,\ extrataxes=:tax2,\ taxmodel=:taxmodel, \ photo=:photo, \ category=:category, \ department=:department, \ subcategory=:subcategory, \ points=:points, \ alphacode=:alphacode, \ vendorcode=:vendorcode, \ lastproviderid=:lastproviderid, \ isARawProduct=:isRaw, \ isAGroup=:isGroup, \ groupElements=:ge, \ groupPriceDrop=:groupPriceDrop, \ isNotDiscountable=:NonDiscountable, \ hasUnlimitedStock=:unlimitedStock \ WHERE code=:id;"); query.bindValue(":newcode", info.code); query.bindValue(":name", info.desc); query.bindValue(":price", info.price); query.bindValue(":stock", info.stockqty); query.bindValue(":cost", info.cost); query.bindValue(":measure", info.units); query.bindValue(":tax1", info.tax); query.bindValue(":tax2", info.extratax); query.bindValue(":photo", info.photo); query.bindValue(":department", info.department); query.bindValue(":category", info.category); query.bindValue(":subcategory", info.subcategory); query.bindValue(":points", info.points); query.bindValue(":id", oldcode); query.bindValue(":alphacode", info.alphaCode); query.bindValue(":vendorcode", info.vendorCode); query.bindValue(":lastproviderid", info.lastProviderId); query.bindValue(":isGroup", info.isAGroup); query.bindValue(":isRaw", info.isARawProduct); query.bindValue(":ge", info.groupElementsStr); query.bindValue(":groupPriceDrop", info.groupPriceDrop); query.bindValue(":taxmodel", info.taxmodelid); query.bindValue(":unlimitedStock", info.hasUnlimitedStock); query.bindValue(":NonDiscountable", info.isNotDiscountable); if (!query.exec()) setError(query.lastError().text()); else result=true; return result; } bool Azahar::decrementProductStock(qulonglong code, double qty, QDate date) { bool result = false; double qtys=qty; double nqty = 0; if (!db.isOpen()) db.open(); ProductInfo p = getProductInfo( QString::number(code) ); if ( p.hasUnlimitedStock ) nqty = 0; //not let unlimitedStock products to be decremented. else nqty = qty; // nqty is the qty to ADD or DEC, qtys is the qty to ADD_TO_SOLD_UNITS only. QSqlQuery query(db); query.prepare("UPDATE products SET datelastsold=:dateSold , stockqty=stockqty-:qty , soldunits=soldunits+:qtys WHERE code=:id"); query.bindValue(":id", code); query.bindValue(":qty", nqty); query.bindValue(":qtys", qtys); query.bindValue(":dateSold", date.toString("yyyy-MM-dd")); if (!query.exec()) setError(query.lastError().text()); else result=true; //qDebug()<<"DECREMENT Product Stock -- Rows Affected:"<<query.numRowsAffected(); return result; } bool Azahar::decrementGroupStock(qulonglong code, double qty, QDate date) { bool result = true; if (!db.isOpen()) db.open(); QSqlQuery query(db); ProductInfo info = getProductInfo(QString::number(code)); QStringList lelem = info.groupElementsStr.split(","); foreach(QString ea, lelem) { qulonglong c = ea.section('/',0,0).toULongLong(); double q = ea.section('/',1,1).toDouble(); //ProductInfo pi = getProductInfo(QString::number(c)); //FOR EACH ELEMENT, DECREMENT PRODUCT STOCK result = result && decrementProductStock(c, q*qty, date); } return result; } /// WARNING: This method is DECREMENTING soldunits... not used in iotposview.cpp nor iotstockview.cpp !!!!! /// Do not use when doing PURCHASES in iotstock! bool Azahar::incrementProductStock(qulonglong code, double qty) { bool result = false; if (!db.isOpen()) db.open(); QSqlQuery query(db); double qtys=qty; double nqty=0; ProductInfo p = getProductInfo( QString::number(code) ); if ( p.hasUnlimitedStock ) nqty = 0; //not let unlimitedStock products to be decremented. else nqty = qty; // nqty is the qty to ADD or DEC, qtys is the qty to ADD_TO_SOLD_UNITS only. query.prepare("UPDATE products SET stockqty=stockqty+:qty , soldunits=soldunits-:qtys WHERE code=:id"); query.bindValue(":id", code); query.bindValue(":qty", nqty); query.bindValue(":qtys", qtys); if (!query.exec()) setError(query.lastError().text()); else result=true; //qDebug()<<"Increment Stock - Rows:"<<query.numRowsAffected(); return result; } /// WARNING: This method is DECREMENTING soldunits... not used in iotposview.cpp nor iotstockview.cpp !!!!! /// Do not use when doing PURCHASES in iotstock! bool Azahar::incrementGroupStock(qulonglong code, double qty) { bool result = true; if (!db.isOpen()) db.open(); QSqlQuery query(db); ProductInfo info = getProductInfo(QString::number(code)); QStringList lelem = info.groupElementsStr.split(","); foreach(QString ea, lelem) { qulonglong c = ea.section('/',0,0).toULongLong(); double q = ea.section('/',1,1).toDouble(); //ProductInfo pi = getProductInfo(c); //FOR EACH ELEMENT, DECREMENT PRODUCT STOCK result = result && incrementProductStock(c, q*qty); } return result; } bool Azahar::deleteProduct(qulonglong code) { bool result = false; if (!db.isOpen()) db.open(); QSqlQuery query(db); query = QString("DELETE FROM products WHERE code=%1").arg(code); if (!query.exec()) setError(query.lastError().text()); else result=true; /** @note & TODO: Document this for the user. * If a discount exists in the offers table for the deleted product, the offer will be deleted also. **/ QSqlQuery queryX(db); if (queryX.exec(QString("Select id from offers where product_id=%1").arg(code) )) { while (queryX.next()) { int fieldId = queryX.record().indexOf("id"); qulonglong oId = queryX.value(fieldId).toULongLong(); deleteOffer(oId); qDebug()<<" **NOTE** Deleting Existing Offer for the deleted Product"; } } return result; } double Azahar::getProductDiscount(qulonglong code, bool isGroup) { double result = 0.0; if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery query2(db); ProductInfo p = getProductInfo( QString::number(code) ); if ( p.isNotDiscountable ) return 0.0; QString qry = QString("SELECT * FROM offers WHERE product_id=%1").arg(code); if (!query2.exec(qry)) { setError(query2.lastError().text()); } else { QList<double> descuentos; descuentos.clear(); while (query2.next()) { int fieldDisc = query2.record().indexOf("discount"); int fieldDateStart = query2.record().indexOf("datestart"); int fieldDateEnd = query2.record().indexOf("dateend"); double descP= query2.value(fieldDisc).toDouble(); QDate dateStart = query2.value(fieldDateStart).toDate(); QDate dateEnd = query2.value(fieldDateEnd).toDate(); QDate now = QDate::currentDate(); //See if the offer is in a valid range... if (isGroup) descuentos.append(descP); else if ((dateStart<dateEnd) && (dateStart<=now) && (dateEnd>=now) ) { //save all discounts here and decide later to return the bigger valid discount. descuentos.append(descP); } } //now which is the bigger valid discount? qSort(descuentos.begin(), descuentos.end(), qGreater<int>()); if (!descuentos.isEmpty()) { //get the first item, which is the greater one. result = descuentos.first(); ///returns the discount percentage! } else result = 0; } } else { setError(db.lastError().text()); } return result; } QList<pieProdInfo> Azahar::getTop5SoldProducts() { QList<pieProdInfo> products; products.clear(); pieProdInfo info; QSqlQuery query(db); if (query.exec("SELECT name,soldunits,units,code FROM products WHERE (soldunits>0 AND isARawProduct=false) ORDER BY soldunits DESC LIMIT 5")) { while (query.next()) { int fieldName = query.record().indexOf("name"); int fieldUnits = query.record().indexOf("units"); int fieldSoldU = query.record().indexOf("soldunits"); int fieldCode = query.record().indexOf("code"); int unit = query.value(fieldUnits).toInt(); info.name = query.value(fieldName).toString(); info.count = query.value(fieldSoldU).toDouble(); info.unitStr = getMeasureStr(unit); info.code = query.value(fieldCode).toULongLong(); products.append(info); } } else { setError(query.lastError().text()); } return products; } double Azahar::getTopFiveMaximum() { double result = 0; QSqlQuery query(db); if (query.exec("SELECT soldunits FROM products WHERE (soldunits>0 AND isARawProduct=false) ORDER BY soldunits DESC LIMIT 5")) { if (query.first()) { int fieldSoldU = query.record().indexOf("soldunits"); result = query.value(fieldSoldU).toDouble(); } } else { setError(query.lastError().text()); } return result; } double Azahar::getAlmostSoldOutMaximum(int max) { double result = 0; QSqlQuery query(db); if (query.exec(QString("SELECT stockqty FROM products WHERE (isARawProduct=false AND isAGroup=false AND stockqty<=%1) ORDER BY stockqty DESC LIMIT 5").arg(max))) { if (query.first()) { int fieldSoldU = query.record().indexOf("stockqty"); result = query.value(fieldSoldU).toDouble(); } } else { setError(query.lastError().text()); } return result; } QList<pieProdInfo> Azahar::getAlmostSoldOutProducts(int max) { QList<pieProdInfo> products; products.clear(); pieProdInfo info; QSqlQuery query(db); //NOTE: Check lower limit for the soldunits range... query.prepare("SELECT name,stockqty,units,code FROM products WHERE (isARawProduct=false AND isAGroup=false AND stockqty<=:maxV) ORDER BY stockqty ASC LIMIT 5"); query.bindValue(":maxV", max); // query.bindValue(":minV", min); if (query.exec()) { while (query.next()) { int fieldName = query.record().indexOf("name"); int fieldUnits = query.record().indexOf("units"); int fieldStock = query.record().indexOf("stockqty"); int fieldCode = query.record().indexOf("code"); int unit = query.value(fieldUnits).toInt(); info.name = query.value(fieldName).toString(); info.count = query.value(fieldStock).toDouble(); info.code = query.value(fieldCode).toULongLong(); info.unitStr = getMeasureStr(unit); products.append(info); } } else { setError(query.lastError().text()); qDebug()<<lastError(); } return products; } //returns soldout products only if the product is NOT a group. QList<ProductInfo> Azahar::getSoldOutProducts() { QList<ProductInfo> products; products.clear(); ProductInfo info; QSqlQuery query(db); query.prepare("SELECT code FROM products WHERE stockqty=0 and isAgroup=false ORDER BY code ASC;"); if (query.exec()) { while (query.next()) { int fieldCode = query.record().indexOf("code"); info = getProductInfo(query.value(fieldCode).toString()); products.append(info); } } else { setError(query.lastError().text()); qDebug()<<lastError(); } return products; } //also discard group products. and unlimited stock ones... QList<ProductInfo> Azahar::getLowStockProducts(double min) { QList<ProductInfo> products; products.clear(); ProductInfo info; QSqlQuery query(db); query.prepare("SELECT code FROM products WHERE (stockqty<=:minV and stockqty>1 and isAGroup=false and hasUnlimitedStock=false) ORDER BY code,stockqty ASC;"); query.bindValue(":minV", min); if (query.exec()) { while (query.next()) { int fieldCode = query.record().indexOf("code"); info = getProductInfo(query.value(fieldCode).toString()); products.append(info); } } else { setError(query.lastError().text()); qDebug()<<lastError(); } return products; } //The list will not include groups or packages QList<ProductInfo> Azahar::getAllProducts() { QList<ProductInfo> products; products.clear(); ProductInfo info; QSqlQuery query(db); query.prepare("SELECT code,stockqty FROM products WHERE isAGroup=false ORDER BY code,stockqty ASC;"); if (query.exec()) { while (query.next()) { int fieldCode = query.record().indexOf("code"); info = getProductInfo(query.value(fieldCode).toString()); products.append(info); } } else { setError(query.lastError().text()); qDebug()<<lastError(); } return products; } qulonglong Azahar::getLastProviderId(qulonglong code) { qulonglong result = 0; QSqlQuery query(db); query.prepare("SELECT lastproviderid FROM products WHERE code=:code"); query.bindValue(":code", code); if (query.exec()) { while (query.next()) { int fieldProv = query.record().indexOf("lastproviderid"); result = query.value(fieldProv).toULongLong(); } } else { setError(query.lastError().text()); qDebug()<<lastError(); } return result; } bool Azahar::updateProductLastProviderId(qulonglong code, qulonglong provId) { bool result = false; if (!db.isOpen()) db.open(); QSqlQuery query(db); query.prepare("UPDATE products SET lastproviderid=:provid WHERE code=:id"); query.bindValue(":id", code); query.bindValue(":provid", provId); if (!query.exec()) setError(query.lastError().text()); else result=true; qDebug()<<"Rows Affected:"<<query.numRowsAffected(); return result; } QList<ProductInfo> Azahar::getGroupProductsList(qulonglong id, bool notConsiderDiscounts) { //qDebug()<<"getGroupProductsList..."; QList<ProductInfo> pList; if (!db.isOpen()) db.open(); if (db.isOpen()) { QString ge = getProductGroupElementsStr(id); //DONOT USE getProductInfo... this will cause an infinite loop because at that method this method is called trough getGroupAverageTax //qDebug()<<"elements:"<<ge; if (ge.isEmpty()) return pList; QStringList pq = ge.split(","); foreach(QString str, pq) { qulonglong c = str.section('/',0,0).toULongLong(); double q = str.section('/',1,1).toDouble(); //get info ProductInfo pi = getProductInfo(QString::number(c), notConsiderDiscounts); pi.qtyOnList = q; pList.append(pi); //qDebug()<<" code:"<<c<<" qty:"<<q; } } return pList; } //NOTE: This method just get the average tax, it does not make any other calculation. // When all the products in the group has a same tax rate, the average tax is the same and // tax in money for the group is fine (not unbalanced), but when is not the same and the difference is much // then the average tax would have an impact, For example: // A group with TWO products : // product 1: Price: 10, tax:15% // product 2: Price 100, tax 1% // The average tax is 8%, its equally for the two products but the second one has a lower tax. // The tax charged to the group with the average tax is $8.8 // The tax charged to the group with each product tax is $2.15 // So the tax is not fine in this case. This means this method is not accurate for all cases. // DEPRECATED /* double Azahar::getGroupAverageTax(qulonglong id) { qDebug()<<"Getting averate tax for id:"<<id; double result = 0; double sum = 0; QList<ProductInfo> pList = getGroupProductsList(id); foreach( ProductInfo info, pList) { sum += info.tax + info.extratax; ///sum += getTotalTaxPercent(info.taxElements); FOR when taxmodels are implemented } result = sum/pList.count(); qDebug()<<"Group average tax: "<<result <<" sum:"<<sum<<" count:"<<pList.count(); return result; } */ /*DEPRECATED double Azahar::getGroupTotalTax(qulonglong id) { qDebug()<<"Getting total tax for id:"<<id; double result = 0; double sum = 0; QList<ProductInfo> pList = getGroupProductsList(id); foreach( ProductInfo info, pList) { sum += info.tax + info.extratax; } result = sum; qDebug()<<" TOTAL tax:"<<sum; return result; }*/ //This method replaces the two above deprecated methods. ///NOTE: Aug 17 2011: this tax does not take into account the ocassional discounts or price changes. It may be false. GroupInfo Azahar::getGroupPriceAndTax(ProductInfo pi) { GroupInfo gInfo; gInfo.price = 0; gInfo.taxMoney = 0; gInfo.tax = 0; gInfo.cost = 0; gInfo.count = 0; gInfo.priceDrop = pi.groupPriceDrop; gInfo.name = pi.desc; if ( pi.code <= 0 ) return gInfo; QList<ProductInfo> plist = getGroupProductsList(pi.code, true); //for getting products with taxes not including discounts. foreach(ProductInfo info, plist) { info.price = (info.price -info.price*(pi.groupPriceDrop/100)); info.totaltax = info.price * info.qtyOnList * (info.tax/100) + info.price * info.qtyOnList * (info.extratax/100); gInfo.price += info.price * info.qtyOnList; gInfo.cost += info.cost * info.qtyOnList; gInfo.taxMoney += info.totaltax*info.qtyOnList; gInfo.count += info.qtyOnList; bool yes = false; if (info.stockqty >= info.qtyOnList ) yes = true; gInfo.isAvailable = (gInfo.isAvailable && yes ); qDebug()<<" < GROUP - EACH ONE > Product: "<<info.desc<<" Price with p-drop: "<<info.price<<" taxMoney: "<<info.totaltax*info.qtyOnList<<" info.tax:"<<info.tax<<" info.extataxes:"<<info.extratax; gInfo.productsList.insert( info.code, info ); } foreach(ProductInfo info, gInfo.productsList) { gInfo.tax += (info.totaltax*info.qtyOnList/gInfo.price)*100; qDebug()<<" < GROUP TAX > qtyOnList:"<<info.qtyOnList<<" tax money for product: "<<info.totaltax<<" group price:"<<gInfo.price<<" taxMoney for group:"<<gInfo.taxMoney<<" tax % for group:"<< gInfo.tax<<" Group cost:"<<gInfo.cost; } return gInfo; } QString Azahar::getProductGroupElementsStr(qulonglong id) { QString result; if (db.isOpen()) { QString qry = QString("SELECT groupElements from products WHERE code=%1").arg(id); QSqlQuery query(db); if (!query.exec(qry)) { int errNum = query.lastError().number(); QSqlError::ErrorType errType = query.lastError().type(); QString error = query.lastError().text(); QString details = i18n("Error #%1, Type:%2\n'%3'",QString::number(errNum), QString::number(errType),error); } if (query.size() <= 0) setError(i18n("Error serching product id %1, Rows affected: %2", id,query.size())); else { while (query.next()) { int field = query.record().indexOf("groupElements"); result = query.value(field).toString(); } } } return result; } void Azahar::updateGroupPriceDrop(qulonglong code, double pd) { if (db.isOpen()) { QSqlQuery query(db); query.prepare("UPDATE products SET groupPriceDrop=:pdrop WHERE code=:id"); query.bindValue(":id", code); query.bindValue(":pdrop", pd); if (!query.exec()) setError(query.lastError().text()); qDebug()<<"<*> updateGroupPriceDrop | Rows Affected:"<<query.numRowsAffected(); } } void Azahar::updateGroupElements(qulonglong code, QString elementsStr) { if (db.isOpen()) { QSqlQuery query(db); query.prepare("UPDATE products SET groupElements=:elements WHERE code=:id"); query.bindValue(":id", code); query.bindValue(":elements", elementsStr); if (!query.exec()) setError(query.lastError().text()); qDebug()<<"<*> updateGroupElements | Rows Affected:"<<query.numRowsAffected(); } } //Bundles QList<BundleInfo> Azahar::getBundleInfo(qulonglong productId) { QList<BundleInfo> list; if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery query(db); query.prepare("SELECT * from bundle_same WHERE product_id=:pid"); query.bindValue(":pid", productId); if (!query.exec()) {setError(query.lastError().text()); qDebug()<<"<*> ERROR: "<<query.lastError();} else { while (query.next()) { int fieldQty = query.record().indexOf("qty"); int fieldPrice= query.record().indexOf("price"); BundleInfo info; info.product_id = productId; info.price = query.value(fieldPrice).toDouble(); info.qty = query.value(fieldQty).toDouble(); list << info; } } } return list; } BundleInfo Azahar::getMaxBundledForProduct(qulonglong pId) { BundleInfo result; result.product_id = pId; result.qty = 0; result.price = 0; if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery query(db); query.prepare("SELECT * from bundle_same WHERE product_id=:pid ORDER BY qty DESC LIMIT 1"); query.bindValue(":pid", pId); if (!query.exec()) {setError(query.lastError().text()); qDebug()<<"<*> ERROR: "<<query.lastError();} else { while (query.next()) { int fieldQty = query.record().indexOf("qty"); int fieldPrice= query.record().indexOf("price"); result.price = query.value(fieldPrice).toDouble(); result.qty = query.value(fieldQty).toDouble(); } } } return result; } double Azahar::getBundlePriceFor(qulonglong pId) { double result = 0; if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery query(db); query.prepare("SELECT price from bundle_same WHERE product_id=:pid"); query.bindValue(":pid", pId); if (!query.exec()) {setError(query.lastError().text()); qDebug()<<"<*> ERROR: "<<query.lastError();} else { while (query.next()) { int fieldPrice= query.record().indexOf("price"); result = query.value(fieldPrice).toDouble(); } } } return result; } //DEPARTMENTS bool Azahar::insertDepartment(QString text) { bool result=false; if (!db.isOpen()) db.open(); QSqlQuery query(db); query.prepare("INSERT INTO departments (text) VALUES (:text);"); query.bindValue(":text", text); if (!query.exec()) setError(query.lastError().text()); else result = true; return result; } bool Azahar::updateDepartment(qulonglong id, QString t) { bool result=false; if (!db.isOpen()) db.open(); QSqlQuery query(db); query.prepare("UPDATE departments set text=:text WHERE id=:id;"); query.bindValue(":text", t); query.bindValue(":id", id); if (!query.exec()) { setError(query.lastError().text()); qDebug()<<"ERROR:"<<query.lastError().text(); } else result = true; return result; } QHash<QString, int> Azahar::getDepartmentsHash() { QHash<QString, int> result; result.clear(); if (!db.isOpen()) db.open(); //if (db.isOpen()) { QSqlQuery myQuery(db); if (myQuery.exec("select * from departments;")) { while (myQuery.next()) { int fieldId = myQuery.record().indexOf("id"); int fieldText = myQuery.record().indexOf("text"); int id = myQuery.value(fieldId).toInt(); QString text = myQuery.value(fieldText).toString(); result.insert(text, id); } } else { qDebug()<<"ERROR: "<<myQuery.lastError(); } //} return result; } QStringList Azahar::getDepartmentsList() { QStringList result; result.clear(); if (!db.isOpen()) db.open(); //if (db.isOpen()) { QSqlQuery myQuery(db); if (myQuery.exec("select text from departments;")) { while (myQuery.next()) { int fieldText = myQuery.record().indexOf("text"); QString text = myQuery.value(fieldText).toString(); result.append(text); } } else { qDebug()<<"ERROR: "<<myQuery.lastError(); } //} return result; } qulonglong Azahar::getDepartmentId(QString texto) { qulonglong result=0; if (!db.isOpen()) db.open(); //if (db.isOpen()) { QSqlQuery myQuery(db); QString qryStr = QString("SELECT departments.id FROM departments WHERE text='%1';").arg(texto); if (myQuery.exec(qryStr) ) { while (myQuery.next()) { int fieldId = myQuery.record().indexOf("id"); qulonglong id= myQuery.value(fieldId).toULongLong(); result = id; } } else { setError(myQuery.lastError().text()); } //} return result; } QString Azahar::getDepartmentStr(qulonglong id) { QString result; QSqlQuery query(db); QString qstr = QString("select text from departments where id=%1;").arg(id); if (query.exec(qstr)) { while (query.next()) { int fieldText = query.record().indexOf("text"); result = query.value(fieldText).toString(); } } else { setError(query.lastError().text()); } return result; } bool Azahar::deleteDepartment(qulonglong id) { bool result = false; if (!db.isOpen()) db.open(); QSqlQuery query(db); query = QString("DELETE FROM departments WHERE departments.id=%1").arg(id); if (!query.exec()) setError(query.lastError().text()); else result=true; qDebug()<<"DEPARTMENT "<<id<<" DELETED:"<<result; //Now, delete any m2m relation for the category... //NOTE: What to do here, delete relations or leave it as they are and let responsibility to the administrator to fix incoherences? //qDebug()<<"IF THE DELETED DEPARTMENT HAS CHILD CATEGORIES, THEN YOU MUST FIX MANUALLY THE INCONSISTENCE. WE ARE GOING TO LEAVE ORPHAN CATEGORIES, INSTEAD OF DELETE THEM."; //NOTE: Or delete the links? I think doing this is not dangerous because we are not deleting the categories itself, only the links between dep->cat. // if the categories had only this links then the categories will be orphans. QSqlQuery queryX(db); queryX.prepare("DELETE FROM m2m_department_category WHERE department=:id"); queryX.bindValue(":id", id); bool m2mOK = queryX.exec(); result = (result && m2mOK); if (!m2mOK) setError(query.lastError().text()); qDebug()<<" --> M2M Relation for department_category DELETED:"<<m2mOK; return result; } bool Azahar::m2mDepartmentCategoryExists(qulonglong d, qulonglong c) { bool result = false; QSqlQuery query(db); QString qstr = QString("select * from m2m_department_category where department=%1 and category=%2;").arg(d).arg(c); if (query.exec(qstr)) { while (query.next()) { int fieldD = query.record().indexOf("department"); int fieldC = query.record().indexOf("category"); if ( query.value(fieldD).toULongLong() == d && query.value(fieldC).toULongLong() == c ) return true; } } else { setError(query.lastError().text()); } return result; } bool Azahar::m2mDepartmentCategoryRemove(qulonglong d, qulonglong c) { bool result = false; if (!db.isOpen()) db.open(); QSqlQuery queryX(db); queryX.prepare("DELETE FROM m2m_department_category WHERE department=:dep AND category=:cat;"); queryX.bindValue(":dep", d); queryX.bindValue(":cat", c); result = queryX.exec(); if (!result) { qDebug()<<"ERROR REMOVING CONNECTION BETWEEN DEP->CAT:"<<d<<"->"<<c<<" |"<<queryX.lastError().text(); setError(queryX.lastError().text()); } return result; } bool Azahar::insertM2MDepartmentCategory(qulonglong depId, qulonglong catId) { bool result=false; if (!db.isOpen()) db.open(); //first, check if the department->category already exists. if ( m2mDepartmentCategoryExists(depId, catId) ) { qDebug()<<"m2m Department -> Category Already exists!"; return false; } //ok it does not exists, create the connection. QSqlQuery query(db); query.prepare("INSERT INTO m2m_department_category (department, category) VALUES (:dep, :cat);"); query.bindValue(":dep", depId); query.bindValue(":cat", catId); if (!query.exec()) { setError(query.lastError().text()); qDebug()<<"Error inserting m2m_department_category: "<<query.lastError().text(); result = false; } else result = true; return result; } //CATEGORIES bool Azahar::insertCategory(QString text) { bool result=false; if (!db.isOpen()) db.open(); QSqlQuery query(db); query.prepare("INSERT INTO categories (text) VALUES (:text);"); query.bindValue(":text", text); if (!query.exec()) setError(query.lastError().text()); else result = true; // else { // //get the newly created category id. // qulonglong cId = getCategoryId(text); // QSqlQuery queryB(db); // //Now, insert the m2m relation, indicated by parent. // queryB.prepare("INSERT INTO m2m_department_category (department, category) VALUES(:dep, :cat);"); // queryB.bindValue(":dep", parent); // queryB.bindValue(":cat", cId); // // result = queryB.exec(); // qDebug()<<"INSERTED CATEGORY OK, INSERTING m2m_department_category:"<<result; // } return result; } bool Azahar::updateCategory(qulonglong id, QString t) { bool result=false; if (!db.isOpen()) db.open(); QSqlQuery query(db); query.prepare("UPDATE categories set text=:text WHERE catid=:id;"); query.bindValue(":text", t); query.bindValue(":id", id); if (!query.exec()) { setError(query.lastError().text()); qDebug()<<"ERROR:"<<query.lastError().text(); } else result = true; return result; } QHash<QString, int> Azahar::getCategoriesHash() { QHash<QString, int> result; result.clear(); if (!db.isOpen()) db.open(); //if (db.isOpen()) { QSqlQuery myQuery(db); if (myQuery.exec("select * from categories;")) { while (myQuery.next()) { int fieldId = myQuery.record().indexOf("catid"); int fieldText = myQuery.record().indexOf("text"); int id = myQuery.value(fieldId).toInt(); QString text = myQuery.value(fieldText).toString(); result.insert(text, id); } } else { qDebug()<<"ERROR: "<<myQuery.lastError(); } //} return result; } QStringList Azahar::getCategoriesList() { QStringList result; result.clear(); if (!db.isOpen()) db.open(); //if (db.isOpen()) { QSqlQuery myQuery(db); if (myQuery.exec("select text from categories;")) { while (myQuery.next()) { int fieldText = myQuery.record().indexOf("text"); QString text = myQuery.value(fieldText).toString(); result.append(text); } } else { qDebug()<<"ERROR: "<<myQuery.lastError(); } //} return result; } qulonglong Azahar::getCategoryId(QString texto) { qulonglong result=0; if (!db.isOpen()) db.open(); //if (db.isOpen()) { QSqlQuery myQuery(db); QString qryStr = QString("SELECT categories.catid FROM categories WHERE text='%1';").arg(texto); if (myQuery.exec(qryStr) ) { while (myQuery.next()) { int fieldId = myQuery.record().indexOf("catid"); qulonglong id= myQuery.value(fieldId).toULongLong(); result = id; } } else { setError(myQuery.lastError().text()); } //} return result; } QString Azahar::getCategoryStr(qulonglong id) { QString result; QSqlQuery query(db); QString qstr = QString("select text from categories where catid=%1;").arg(id); if (query.exec(qstr)) { while (query.next()) { int fieldText = query.record().indexOf("text"); result = query.value(fieldText).toString(); } } else { setError(query.lastError().text()); } return result; } bool Azahar::deleteCategory(qulonglong id) { bool result = false; if (!db.isOpen()) db.open(); QSqlQuery query(db); query = QString("DELETE FROM categories WHERE catid=%1").arg(id); if (!query.exec()) setError(query.lastError().text()); else result=true; qDebug()<<"CATEGORY "<<id<<" DELETED:"<<result; //Now, delete any m2m relation for the subcategory... QSqlQuery queryX(db); queryX.prepare("DELETE FROM m2m_department_category WHERE category=:id"); queryX.bindValue(":id", id); bool m2mOK = queryX.exec(); result = (result && m2mOK); if (!m2mOK) setError(query.lastError().text()); qDebug()<<" --> M2M Relation for department_category DELETED:"<<m2mOK; return result; } bool Azahar::m2mCategorySubcategoryExists(qulonglong c, qulonglong s) { bool result = false; QSqlQuery query(db); QString qstr = QString("select * from m2m_category_subcategory where category=%1 and subcategory=%2;").arg(c).arg(s); if (query.exec(qstr)) { while (query.next()) { int fieldC = query.record().indexOf("category"); int fieldS = query.record().indexOf("subcategory"); if ( query.value(fieldC).toULongLong() == c && query.value(fieldS).toULongLong() == s ) return true; } } else { setError(query.lastError().text()); } return result; } bool Azahar::insertM2MCategorySubcategory(qulonglong catId, qulonglong subcatId) { bool result=false; if (!db.isOpen()) db.open(); //first, check if the category->subcategory already exists. if ( m2mCategorySubcategoryExists(catId, subcatId) ) { qDebug()<<"m2m Category -> subCategory Already exists!"; return false; } //ok it does not exists, create the connection. QSqlQuery query(db); query.prepare("INSERT INTO m2m_category_subcategory (category, subcategory) VALUES (:cat, :subcat);"); query.bindValue(":cat", catId); query.bindValue(":subcat", subcatId); if (!query.exec()) { setError(query.lastError().text()); qDebug()<<"Error inserting m2m_category_subcategory: "<<query.lastError().text(); result = false; } else result = true; return result; } bool Azahar::m2mCategorySubcategoryRemove(qulonglong c, qulonglong sc) { bool result = false; if (!db.isOpen()) db.open(); QSqlQuery queryX(db); queryX.prepare("DELETE FROM m2m_category_subcategory WHERE category=:cat AND subcategory=:scat;"); queryX.bindValue(":cat", c); queryX.bindValue(":scat", sc); result = queryX.exec(); if (!result) { qDebug()<<"ERROR REMOVING CONNECTION BETWEEN CAT->SUBCAT:"<<c<<"->"<<sc<<" |"<<queryX.lastError().text(); setError(queryX.lastError().text()); } return result; } //SUBCATEGORIES QHash<QString, int> Azahar::getSubCategoriesHash() { QHash<QString, int> result; result.clear(); if (!db.isOpen()) db.open(); //if (db.isOpen()) { QSqlQuery myQuery(db); if (myQuery.exec("select * from subcategories;")) { while (myQuery.next()) { int fieldId = myQuery.record().indexOf("id"); int fieldText = myQuery.record().indexOf("text"); int id = myQuery.value(fieldId).toInt(); QString text = myQuery.value(fieldText).toString(); result.insert(text, id); } } else { qDebug()<<"ERROR: "<<myQuery.lastError(); } //} return result; } QStringList Azahar::getSubCategoriesList() { QStringList result; result.clear(); //result.append(" --- "); if (!db.isOpen()) db.open(); //if (db.isOpen()) { ///NOTE: I dont know why this is not working! it says is not open, but without this check it works. It fails when doing some cycling, like a subcategoryEditor inside a subcategoryEditor. The first work, the second does not... qDebug()<<"Getting subcategories list... db is ok"; QSqlQuery myQuery(db); if (myQuery.exec("select * from subcategories;")) { while (myQuery.next()) { int fieldText = myQuery.record().indexOf("text"); QString text = myQuery.value(fieldText).toString(); result.append(text); } } else { qDebug()<<"ERROR: "<<myQuery.lastError(); } //} return result; } QStringList Azahar::getCategoriesList(const qulonglong parent) { QStringList result; result.clear(); //result.append(" --- "); if (!db.isOpen()) db.open(); QSqlQuery myQuery(db); QString queryTxt; if (parent == 0) queryTxt = QString("SELECT text FROM categories;"); //get all categories... else queryTxt = QString("SELECT \ M2M.category AS M2M_CAT, C.text AS text \ FROM categories AS C, m2m_department_category as M2M \ WHERE M2M.department=%1 AND C.catid=M2M.category;").arg(parent); if (myQuery.exec(queryTxt)) { while (myQuery.next()) { int fieldText = myQuery.record().indexOf("text"); QString text = myQuery.value(fieldText).toString(); result.append(text); } } else { qDebug()<<"ERROR: "<<myQuery.lastError(); } return result; } //This method gets the subcategories list for a parent category. If parent=0, returns all subcategories. //NOTE & WARNING: when parent=0 also this could mean only return root categories. But we are not doing this here. QStringList Azahar::getSubCategoriesList(qulonglong parent) { QStringList result; result.clear(); //result.append(" --- "); if (!db.isOpen()) db.open(); //if (db.isOpen()) { QSqlQuery myQuery(db); QString queryTxt; if (parent == 0) queryTxt = QString("SELECT text FROM subcategories;"); //get all subcategories... else //queryTxt = QString("SELECT text FROM subcategories WHERE parent=%1;").arg(parent); queryTxt = QString("SELECT \ M2M.subcategory AS M2M_SUBCAT, S.text AS text \ FROM subcategories as S, m2m_category_subcategory as M2M \ WHERE M2M.category=%1 AND S.id=M2M.subcategory;").arg(parent); if (myQuery.exec(queryTxt)) { while (myQuery.next()) { int fieldText = myQuery.record().indexOf("text"); QString text = myQuery.value(fieldText).toString(); result.append(text); } } else { qDebug()<<"ERROR: "<<myQuery.lastError(); } //} return result; } bool Azahar::insertSubCategory(QString text) { bool result=false; if (!db.isOpen()) db.open(); QSqlQuery query(db); //First, insert the category itself. query.prepare("INSERT INTO subcategories (text) VALUES (:text);"); query.bindValue(":text", text); if (!query.exec()) setError(query.lastError().text()); else result = true; // else { // //get the newly created subcategory id. // qulonglong scId = getSubCategoryId(text); // QSqlQuery queryB(db); // //Now, insert the m2m relation, indicated by parent. // queryB.prepare("INSERT INTO m2m_category_subcategory (category, subcategory) VALUES(:cat, :sub);"); // queryB.bindValue(":sub", scId); // queryB.bindValue(":cat", parent); // // result = queryB.exec(); // qDebug()<<"INSERTED SUBCATEGORY OK, INSERTING m2m_category_subcategory:"<<result; // } return result; } qulonglong Azahar::getSubCategoryId(QString texto) { qulonglong result=0; if (!db.isOpen()) db.open(); //if (db.isOpen()) { QSqlQuery myQuery(db); QString qryStr = QString("SELECT subcategories.id FROM subcategories WHERE text='%1';").arg(texto); if (myQuery.exec(qryStr) ) { while (myQuery.next()) { int fieldId = myQuery.record().indexOf("id"); qulonglong id= myQuery.value(fieldId).toULongLong(); result = id; } } else { setError(myQuery.lastError().text()); } //} return result; } QString Azahar::getSubCategoryStr(qulonglong id) { QString result = ""; QSqlQuery query(db); QString qstr = QString("select text from subcategories where subcategories.id=%1;").arg(id); if (query.exec(qstr)) { while (query.next()) { int fieldText = query.record().indexOf("text"); result = query.value(fieldText).toString(); } } else { setError(query.lastError().text()); } return result; } bool Azahar::deleteSubCategory(qulonglong id) { bool result = false; if (!db.isOpen()) db.open(); QSqlQuery query(db); query = QString("DELETE FROM subcategories WHERE subcategories.id=%1").arg(id); if (!query.exec()) setError(query.lastError().text()); else result=true; qDebug()<<"SUBCATEGORY "<<id<<" DELETED:"<<result; //Now, delete any m2m relation for the subcategory... QSqlQuery queryX(db); queryX.prepare("DELETE FROM m2m_category_subcategory WHERE subcategory=:id"); queryX.bindValue(":id", id); bool m2mOK = queryX.exec(); result = (result && m2mOK); if (!m2mOK) setError(query.lastError().text()); qDebug()<<" --> M2M Relation for category_subcategory DELETED:"<<m2mOK; return result; } //MEASURES bool Azahar::insertMeasure(QString text) { bool result=false; if (!db.isOpen()) db.open(); QSqlQuery query(db); query.prepare("INSERT INTO measures (text) VALUES (:text);"); query.bindValue(":text", text); if (!query.exec()) { setError(query.lastError().text()); } else result=true; return result; } qulonglong Azahar::getMeasureId(QString texto) { qulonglong result=0; if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery myQuery(db); QString qryStr = QString("select measures.id from measures where text='%1';").arg(texto); if (myQuery.exec(qryStr) ) { while (myQuery.next()) { int fieldId = myQuery.record().indexOf("id"); qulonglong id = myQuery.value(fieldId).toULongLong(); result = id; } } else { setError(myQuery.lastError().text()); } } return result; } QString Azahar::getMeasureStr(qulonglong id) { QString result; QSqlQuery query(db); QString qstr = QString("select text from measures where measures.id=%1;").arg(id); if (query.exec(qstr)) { while (query.next()) { int fieldText = query.record().indexOf("text"); result = query.value(fieldText).toString(); } } else { setError(query.lastError().text()); } return result; } QStringList Azahar::getMeasuresList() { QStringList result; result.clear(); if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery myQuery(db); if (myQuery.exec("select text from measures;")) { while (myQuery.next()) { int fieldText = myQuery.record().indexOf("text"); QString text = myQuery.value(fieldText).toString(); result.append(text); } } else { qDebug()<<"ERROR: "<<myQuery.lastError(); } } return result; } bool Azahar::deleteMeasure(qulonglong id) { bool result = false; if (!db.isOpen()) db.open(); QSqlQuery query(db); query = QString("DELETE FROM measures WHERE id=%1").arg(id); if (!query.exec()) setError(query.lastError().text()); else result=true; return result; } //OFFERS bool Azahar::createOffer(OfferInfo info) { bool result=false; QString qryStr; QSqlQuery query(db); if (!db.isOpen()) db.open(); ProductInfo p = getProductInfo( QString::number(info.productCode) ); if ( p.isNotDiscountable ) { setError(i18n("Unable to set an offer/discount for the selected produc because it is NOT DISCOUNTABLE")); return false; } //The product has no offer yet. //NOTE: Now multiple offers supported (to save offers history) qryStr = "INSERT INTO offers (discount, datestart, dateend, product_id) VALUES(:discount, :datestart, :dateend, :code)"; query.prepare(qryStr); query.bindValue(":discount", info.discount ); query.bindValue(":datestart", info.dateStart.toString("yyyy-MM-dd")); query.bindValue(":dateend", info.dateEnd.toString("yyyy-MM-dd")); query.bindValue(":code", info.productCode); if (query.exec()) result = true; else setError(query.lastError().text()); return result; } bool Azahar::deleteOffer(qlonglong id) { bool result=false; if (db.isOpen()) { QString qry = QString("DELETE from offers WHERE offers.id=%1").arg(id); QSqlQuery query(db); if (!query.exec(qry)) { int errNum = query.lastError().number(); QSqlError::ErrorType errType = query.lastError().type(); QString error = query.lastError().text(); QString details = i18n("Error #%1, Type:%2\n'%3'",QString::number(errNum), QString::number(errType),error); } if (query.numRowsAffected() == 1) result = true; else setError(i18n("Error deleting offer id %1, Rows affected: %2", id,query.numRowsAffected())); } return result; } QString Azahar::getOffersFilterWithText(QString text) { QStringList codes; QString result=""; if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery qry(db); QString qryStr= QString("SELECT P.code, P.name, O.product_id FROM offers AS O, products AS P WHERE P.code = O.product_id and P.name REGEXP '%1' ").arg(text); if (!qry.exec(qryStr)) setError(qry.lastError().text()); else { codes.clear(); while (qry.next()) { int fieldId = qry.record().indexOf("code"); qulonglong c = qry.value(fieldId).toULongLong(); codes.append(QString("offers.product_id=%1 ").arg(c)); } result = codes.join(" OR "); } } return result; } bool Azahar::moveOffer(qulonglong oldp, qulonglong newp) { bool result=false; if (!db.isOpen()) db.open(); QSqlQuery q(db); QString qs = QString("UPDATE offers SET product_id=%1 WHERE product_id=%2;").arg(newp).arg(oldp); if (!q.exec( qs )) setError(q.lastError().text()); else result = true; return result; } //USERS bool Azahar::insertUser(UserInfo info) { bool result=false; if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery query(db); query.prepare("INSERT INTO users (username, password, salt, name, address, phone, phone_movil, role, photo) VALUES(:uname, :pass, :salt, :name, :address, :phone, :cell, :rol, :photo)"); query.bindValue(":photo", info.photo); query.bindValue(":uname", info.username); query.bindValue(":name", info.name); query.bindValue(":address", info.address); query.bindValue(":phone", info.phone); query.bindValue(":cell", info.cell); query.bindValue(":pass", info.password); query.bindValue(":salt", info.salt); query.bindValue(":rol", info.role); if (!query.exec()) setError(query.lastError().text()); else result = true; qDebug()<<"USER insert:"<<query.lastError(); //FIXME: We must see error types, which ones are for duplicate KEYS (codes) to advertise the user. }//db open return result; } QHash<QString,UserInfo> Azahar::getUsersHash() { QHash<QString,UserInfo> result; if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery query(db); QString qry = "SELECT * FROM users;"; if (query.exec(qry)) { while (query.next()) { int fielduId = query.record().indexOf("id"); int fieldUsername = query.record().indexOf("username"); int fieldPassword = query.record().indexOf("password"); int fieldSalt = query.record().indexOf("salt"); int fieldName = query.record().indexOf("name"); int fieldRole = query.record().indexOf("role"); // see role numbers at enums.h int fieldPhoto = query.record().indexOf("photo"); //more fields, now im not interested in that... UserInfo info; info.id = query.value(fielduId).toInt(); info.username = query.value(fieldUsername).toString(); info.password = query.value(fieldPassword).toString(); info.salt = query.value(fieldSalt).toString(); info.name = query.value(fieldName).toString(); info.photo = query.value(fieldPhoto).toByteArray(); info.role = query.value(fieldRole).toInt(); result.insert(info.username, info); //qDebug()<<"got user:"<<info.username; } } else { qDebug()<<"**Error** :"<<query.lastError(); } } return result; } UserInfo Azahar::getUserInfo(const qulonglong &userid) { UserInfo info; if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery query(db); QString qry = QString("SELECT * FROM users where id=%1;").arg(userid); if (query.exec(qry)) { while (query.next()) { int fielduId = query.record().indexOf("id"); int fieldUsername = query.record().indexOf("username"); int fieldPassword = query.record().indexOf("password"); int fieldSalt = query.record().indexOf("salt"); int fieldName = query.record().indexOf("name"); int fieldRole = query.record().indexOf("role"); // see role numbers at enums.h int fieldPhoto = query.record().indexOf("photo"); //more fields, now im not interested in that... info.id = query.value(fielduId).toInt(); info.username = query.value(fieldUsername).toString(); info.password = query.value(fieldPassword).toString(); info.salt = query.value(fieldSalt).toString(); info.name = query.value(fieldName).toString(); info.photo = query.value(fieldPhoto).toByteArray(); info.role = query.value(fieldRole).toInt(); //qDebug()<<"got user:"<<info.username; } } else { qDebug()<<"**Error** :"<<query.lastError(); } } return info; } bool Azahar::updateUser(UserInfo info) { bool result=false; if (!db.isOpen()) db.open(); QSqlQuery query(db); query.prepare("UPDATE users SET photo=:photo, username=:uname, name=:name, address=:address, phone=:phone, phone_movil=:cell, salt=:salt, password=:pass, role=:rol WHERE id=:code;"); query.bindValue(":code", info.id); query.bindValue(":photo", info.photo); query.bindValue(":uname", info.username); query.bindValue(":name", info.name); query.bindValue(":address", info.address); query.bindValue(":phone", info.phone); query.bindValue(":cell", info.cell); query.bindValue(":pass", info.password); query.bindValue(":salt", info.salt); query.bindValue(":rol", info.role); if (!query.exec()) setError(query.lastError().text()); else result=true; return result; } QString Azahar::getUserName(QString username) { QString name = ""; if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery queryUname(db); QString qry = QString("SELECT name FROM users WHERE username='%1'").arg(username); if (!queryUname.exec(qry)) { setError(queryUname.lastError().text()); } else { if (queryUname.isActive() && queryUname.isSelect()) { //qDebug()<<"queryUname select && active."; if (queryUname.first()) { //qDebug()<<"queryUname.first()=true"; name = queryUname.value(0).toString(); } } } } else { setError(db.lastError().text()); } return name; } QString Azahar::getUserName(qulonglong id) { QString name = ""; if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery queryUname(db); QString qry = QString("SELECT name FROM users WHERE users.id=%1").arg(id); if (!queryUname.exec(qry)) { setError(queryUname.lastError().text()); } else { if (queryUname.isActive() && queryUname.isSelect()) { //qDebug()<<"queryUname select && active."; if (queryUname.first()) { //qDebug()<<"queryUname.first()=true"; name = queryUname.value(0).toString(); } } } } else { setError(db.lastError().text()); } return name; } QStringList Azahar::getUsersList() { QStringList result; result.clear(); if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery myQuery(db); if (myQuery.exec("select name from users;")) { while (myQuery.next()) { int fieldText = myQuery.record().indexOf("name"); QString text = myQuery.value(fieldText).toString(); result.append(text); } } else { qDebug()<<"ERROR: "<<myQuery.lastError(); } } return result; } unsigned int Azahar::getUserId(QString uname) { unsigned int iD = 0; if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery queryId(db); QString qry = QString("SELECT id FROM users WHERE username='%1'").arg(uname); if (!queryId.exec(qry)) { setError(queryId.lastError().text()); } else { if (queryId.isActive() && queryId.isSelect()) { //qDebug()<<"queryId select && active."; if (queryId.first()) { //qDebug()<<"queryId.first()=true"; iD = queryId.value(0).toUInt(); } } } } else { setError(db.lastError().text()); } return iD; } unsigned int Azahar::getUserIdFromName(QString uname) { unsigned int iD = 0; if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery queryId(db); QString qry = QString("SELECT id FROM users WHERE name='%1'").arg(uname); if (!queryId.exec(qry)) { setError(queryId.lastError().text()); } else { if (queryId.isActive() && queryId.isSelect()) { //qDebug()<<"queryId select && active."; if (queryId.first()) { //qDebug()<<"queryId.first()=true"; iD = queryId.value(0).toUInt(); } } } } else { setError(db.lastError().text()); } return iD; } int Azahar::getUserRole(const qulonglong &userid) { int role = 0; if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery queryId(db); QString qry = QString("SELECT role FROM users WHERE id=%1").arg(userid); if (!queryId.exec(qry)) { setError(queryId.lastError().text()); } else { if (queryId.isActive() && queryId.isSelect()) { //qDebug()<<"queryId select && active."; if (queryId.first()) { //qDebug()<<"queryId.first()=true"; role = queryId.value(0).toInt(); } } } } else { setError(db.lastError().text()); } return role; } bool Azahar::deleteUser(qulonglong id) { bool result = false; if (!db.isOpen()) db.open(); QSqlQuery query(db); query = QString("DELETE FROM users WHERE id=%1").arg(id); if (!query.exec()) setError(query.lastError().text()); else result=true; return result; } //CLIENTS bool Azahar::insertClient(ClientInfo info) { bool result = false; if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery query(db); query.prepare("INSERT INTO clients (name, address, phone, phone_movil, points, discount, photo, since, code) VALUES(:name, :address, :phone, :cell,:points, :discount, :photo, :since, :code)"); query.bindValue(":photo", info.photo); query.bindValue(":points", info.points); query.bindValue(":discount", info.discount); query.bindValue(":name", info.name); query.bindValue(":code", info.code); query.bindValue(":address", info.address); query.bindValue(":phone", info.phone); query.bindValue(":cell", info.cell); query.bindValue(":since", info.since); if (!query.exec()) setError(query.lastError().text()); else result = true; } return result; } bool Azahar::updateClient(ClientInfo info) { bool result=false; if (!db.isOpen()) db.open(); QSqlQuery query(db); query.prepare("UPDATE clients SET photo=:photo, name=:name, code=:code, address=:address, phone=:phone, phone_movil=:cell, points=:points, discount=:disc, since=:since WHERE id=:id;"); query.bindValue(":id", info.id); query.bindValue(":photo", info.photo); query.bindValue(":points", info.points); query.bindValue(":disc", info.discount); query.bindValue(":name", info.name); query.bindValue(":code", info.code); query.bindValue(":address", info.address); query.bindValue(":phone", info.phone); query.bindValue(":cell", info.cell); query.bindValue(":since", info.since); if (!query.exec()) setError(query.lastError().text()); else result = true; return result; } bool Azahar::incrementClientPoints(qulonglong id, qulonglong points) { bool result=false; if (!db.isOpen()) db.open(); QSqlQuery query(db); query.prepare("UPDATE clients SET points=points+:points WHERE id=:code;"); query.bindValue(":code", id); query.bindValue(":points", points); if (!query.exec()) setError(query.lastError().text()); else result = true; return result; } bool Azahar::decrementClientPoints(qulonglong id, qulonglong points) { bool result=false; if (!db.isOpen()) db.open(); QSqlQuery query(db); query.prepare("UPDATE clients SET points=points-:points WHERE id=:code;"); query.bindValue(":code", id); query.bindValue(":points", points); if (!query.exec()) setError(query.lastError().text()); else result = true; return result; } ClientInfo Azahar::getClientInfo(qulonglong clientId) { ClientInfo info; info.name = ""; info.id = 0;//to recognize errors. if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery qC(db); if (qC.exec(QString("select * from clients where id=%1;").arg(clientId))) { while (qC.next()) { int fieldId = qC.record().indexOf("id"); int fieldCode = qC.record().indexOf("code"); int fieldName = qC.record().indexOf("name"); int fieldPoints = qC.record().indexOf("points"); int fieldPhoto = qC.record().indexOf("photo"); int fieldDisc = qC.record().indexOf("discount"); int fieldSince = qC.record().indexOf("since"); int fieldPhone = qC.record().indexOf("phone"); int fieldCell = qC.record().indexOf("phone_movil"); int fieldAdd = qC.record().indexOf("address"); //Should be only one info.id = qC.value(fieldId).toUInt(); info.code = qC.value(fieldCode).toString(); info.name = qC.value(fieldName).toString(); info.points = qC.value(fieldPoints).toULongLong(); info.discount = qC.value(fieldDisc).toDouble(); info.photo = qC.value(fieldPhoto).toByteArray(); info.since = qC.value(fieldSince).toDate(); info.phone = qC.value(fieldPhone).toString(); info.cell = qC.value(fieldCell).toString(); info.address = qC.value(fieldAdd).toString(); } } else { qDebug()<<"ERROR: "<<qC.lastError(); } } return info; } ClientInfo Azahar::getClientInfo(QString clientCode) { ClientInfo info; info.name = ""; info.id = 0;//to recognize errors. if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery qC(db); if (qC.exec(QString("select * from clients WHERE code='%1';").arg(clientCode))) { while (qC.next()) { int fieldId = qC.record().indexOf("id"); int fieldCode = qC.record().indexOf("code"); int fieldName = qC.record().indexOf("name"); int fieldPoints = qC.record().indexOf("points"); int fieldPhoto = qC.record().indexOf("photo"); int fieldDisc = qC.record().indexOf("discount"); int fieldSince = qC.record().indexOf("since"); int fieldPhone = qC.record().indexOf("phone"); int fieldCell = qC.record().indexOf("phone_movil"); int fieldAdd = qC.record().indexOf("address"); info.id = qC.value(fieldId).toUInt(); info.code = qC.value(fieldCode).toString(); info.name = qC.value(fieldName).toString(); info.points = qC.value(fieldPoints).toULongLong(); info.discount = qC.value(fieldDisc).toDouble(); info.photo = qC.value(fieldPhoto).toByteArray(); info.since = qC.value(fieldSince).toDate(); info.phone = qC.value(fieldPhone).toString(); info.cell = qC.value(fieldCell).toString(); info.address = qC.value(fieldAdd).toString(); } } else { qDebug()<<"ERROR: "<<qC.lastError(); } } return info; } QString Azahar::getMainClient() { QString result; ClientInfo info; if (m_mainClient == "undefined") { if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery qC(db); if (qC.exec("select * from clients where id=1;")) { while (qC.next()) { int fieldName = qC.record().indexOf("name"); info.name = qC.value(fieldName).toString(); m_mainClient = info.name; result = info.name; } } else { qDebug()<<"ERROR: "<<qC.lastError(); } } } else result = m_mainClient; return result; } QHash<QString, ClientInfo> Azahar::getClientsHash() { QHash<QString, ClientInfo> result; ClientInfo info; if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery qC(db); if (qC.exec("select * from clients;")) { while (qC.next()) { int fieldId = qC.record().indexOf("id"); int fieldName = qC.record().indexOf("name"); int fieldPoints = qC.record().indexOf("points"); int fieldPhoto = qC.record().indexOf("photo"); int fieldDisc = qC.record().indexOf("discount"); int fieldSince = qC.record().indexOf("since"); int fieldCode = qC.record().indexOf("code"); int fieldAddr = qC.record().indexOf("address"); info.id = qC.value(fieldId).toUInt(); info.name = qC.value(fieldName).toString(); info.points = qC.value(fieldPoints).toULongLong(); info.discount = qC.value(fieldDisc).toDouble(); info.photo = qC.value(fieldPhoto).toByteArray(); info.since = qC.value(fieldSince).toDate(); info.code = qC.value(fieldCode).toString(); info.address = qC.value(fieldAddr).toString(); result.insert(info.name, info); if (info.id == 1) m_mainClient = info.name; } } else { qDebug()<<"ERROR: "<<qC.lastError(); } } return result; } QStringList Azahar::getClientsList() { QStringList result; result.clear(); if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery myQuery(db); if (myQuery.exec("select name from clients;")) { while (myQuery.next()) { int fieldText = myQuery.record().indexOf("name"); QString text = myQuery.value(fieldText).toString(); result.append(text); } } else { qDebug()<<"ERROR: "<<myQuery.lastError(); } } return result; } unsigned int Azahar::getClientId(QString uname) { unsigned int iD = 0; if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery queryId(db); QString qry = QString("SELECT clients.id FROM clients WHERE clients.name='%1'").arg(uname); if (!queryId.exec(qry)) { setError(queryId.lastError().text()); } else { if (queryId.isActive() && queryId.isSelect()) { //qDebug()<<"queryId select && active."; if (queryId.first()) { //qDebug()<<"queryId.first()=true"; iD = queryId.value(0).toUInt(); } } } } else { setError(db.lastError().text()); } return iD; } bool Azahar::deleteClient(qulonglong id) { bool result = false; if (!db.isOpen()) db.open(); QSqlQuery query(db); query = QString("DELETE FROM clients WHERE id=%1").arg(id); if (!query.exec()) setError(query.lastError().text()); else result=true; return result; } //TRANSACTIONS TransactionInfo Azahar::getTransactionInfo(qulonglong id) { TransactionInfo info; info.id = 0; QString qry = QString("SELECT * FROM transactions WHERE id=%1").arg(id); QSqlQuery query; if (!query.exec(qry)) { qDebug()<<query.lastError(); } else { while (query.next()) { int fieldId = query.record().indexOf("id"); int fieldAmount = query.record().indexOf("amount"); int fieldDate = query.record().indexOf("date"); int fieldTime = query.record().indexOf("time"); int fieldPaidWith = query.record().indexOf("paidwith"); int fieldPayMethod = query.record().indexOf("paymethod"); int fieldType = query.record().indexOf("type"); int fieldChange = query.record().indexOf("changegiven"); int fieldState = query.record().indexOf("state"); int fieldUserId = query.record().indexOf("userid"); int fieldClientId = query.record().indexOf("clientid"); int fieldCardNum = query.record().indexOf("cardnumber"); int fieldCardAuth = query.record().indexOf("cardauthnumber"); int fieldItemCount = query.record().indexOf("itemcount"); int fieldItemsList = query.record().indexOf("itemsList"); int fieldDiscount = query.record().indexOf("disc"); int fieldDiscMoney = query.record().indexOf("discmoney"); int fieldPoints = query.record().indexOf("points"); int fieldUtility = query.record().indexOf("utility"); int fieldTerminal = query.record().indexOf("terminalnum"); int fieldTax = query.record().indexOf("totalTax"); int fieldSpecialOrders = query.record().indexOf("specialOrders"); int fieldCardTypeId = query.record().indexOf("cardtype"); info.id = query.value(fieldId).toULongLong(); info.amount = query.value(fieldAmount).toDouble(); info.date = query.value(fieldDate).toDate(); info.time = query.value(fieldTime).toTime(); info.paywith= query.value(fieldPaidWith).toDouble(); info.paymethod = query.value(fieldPayMethod).toInt(); info.type = query.value(fieldType).toInt(); info.changegiven = query.value(fieldChange).toDouble(); info.state = query.value(fieldState).toInt(); info.userid = query.value(fieldUserId).toULongLong(); info.clientid = query.value(fieldClientId).toULongLong(); info.cardnumber= query.value(fieldCardNum).toString();//.replace(0,15,"***************"); //FIXED: Only save last 4 digits; info.cardauthnum=query.value(fieldCardAuth).toString(); info.itemcount = query.value(fieldItemCount).toInt(); info.itemlist = query.value(fieldItemsList).toString(); info.disc = query.value(fieldDiscount).toDouble(); info.discmoney = query.value(fieldDiscMoney).toDouble(); info.points = query.value(fieldPoints).toULongLong(); info.utility = query.value(fieldUtility).toDouble(); info.terminalnum=query.value(fieldTerminal).toInt(); info.totalTax = query.value(fieldTax).toDouble(); info.specialOrders = query.value(fieldSpecialOrders).toString(); info.cardType =query.value(fieldCardTypeId).toInt(); info.cardTypeStr= getCardTypeStr(info.cardType); } } return info; } ProfitRange Azahar::getMonthProfitRange() { QList<TransactionInfo> monthTrans = getMonthTransactionsForPie(); ProfitRange range; QList<double> profitList; TransactionInfo info; for (int i = 0; i < monthTrans.size(); ++i) { info = monthTrans.at(i); profitList.append(info.utility); } if (!profitList.isEmpty()) { qSort(profitList.begin(),profitList.end()); //sorting in ascending order (1,2,3..) range.min = profitList.first(); range.max = profitList.last(); } else {range.min=0.0; range.max=0.0;} return range; } ProfitRange Azahar::getMonthSalesRange() { QList<TransactionInfo> monthTrans = getMonthTransactionsForPie(); ProfitRange range; QList<double> salesList; TransactionInfo info; for (int i = 0; i < monthTrans.size(); ++i) { info = monthTrans.at(i); salesList.append(info.amount); } if (!salesList.isEmpty()) { qSort(salesList.begin(),salesList.end()); //sorting in ascending order (1,2,3..) range.min = salesList.first(); range.max = salesList.last(); } else {range.min=0.0; range.max=0.0;} return range; } QList<TransactionInfo> Azahar::getMonthTransactionsForPie() { ///just return the amount and the profit. QList<TransactionInfo> result; TransactionInfo info; QSqlQuery qryTrans(db); QDate today = QDate::currentDate(); QDate startDate = QDate(today.year(), today.month(), 1); //get the 1st of the month. //NOTE: in the next query, the state and type are hardcoded (not using the enums) because problems when preparing query. qryTrans.prepare("SELECT date,SUM(amount),SUM(utility) from transactions where (date BETWEEN :dateSTART AND :dateEND ) AND (type=1) AND (state=2 OR state=8 OR state=9) GROUP BY date ASC;"); qryTrans.bindValue("dateSTART", startDate.toString("yyyy-MM-dd")); qryTrans.bindValue("dateEND", today.toString("yyyy-MM-dd")); //tCompleted=2, tSell=1. With a placeholder, the value is inserted as a string, and cause the query to fail. if (!qryTrans.exec() ) { int errNum = qryTrans.lastError().number(); QSqlError::ErrorType errType = qryTrans.lastError().type(); QString errStr = qryTrans.lastError().text(); QString details = i18n("Error #%1, Type:%2\n'%3'",QString::number(errNum), QString::number(errType),errStr); setError(details); } else { while (qryTrans.next()) { int fieldAmount = qryTrans.record().indexOf("SUM(amount)"); int fieldProfit = qryTrans.record().indexOf("SUM(utility)"); int fieldDate = qryTrans.record().indexOf("date"); info.amount = qryTrans.value(fieldAmount).toDouble(); info.utility = qryTrans.value(fieldProfit).toDouble(); info.date = qryTrans.value(fieldDate).toDate(); result.append(info); //qDebug()<<"APPENDING:"<<info.date<< " Sales:"<<info.amount<<" Profit:"<<info.utility; } //qDebug()<<"executed query:"<<qryTrans.executedQuery(); //qDebug()<<"Qry size:"<<qryTrans.size(); } return result; } QList<TransactionInfo> Azahar::getMonthTransactions() { QList<TransactionInfo> result; TransactionInfo info; QSqlQuery qryTrans(db); QDate today = QDate::currentDate(); QDate startDate = QDate(today.year(), today.month(), 1); //get the 1st of the month. //NOTE: in the next query, the state and type are hardcoded (not using the enums) because problems when preparing query. qryTrans.prepare("SELECT id,date from transactions where (date BETWEEN :dateSTART AND :dateEND ) AND (type=1) AND (state=2 OR state=8 OR state=9) ORDER BY date,id ASC;"); qryTrans.bindValue("dateSTART", startDate.toString("yyyy-MM-dd")); qryTrans.bindValue("dateEND", today.toString("yyyy-MM-dd")); //tCompleted=2, tSell=1. With a placeholder, the value is inserted as a string, and cause the query to fail. if (!qryTrans.exec() ) { int errNum = qryTrans.lastError().number(); QSqlError::ErrorType errType = qryTrans.lastError().type(); QString errStr = qryTrans.lastError().text(); QString details = i18n("Error #%1, Type:%2\n'%3'",QString::number(errNum), QString::number(errType),errStr); setError(details); } else { while (qryTrans.next()) { int fieldId = qryTrans.record().indexOf("id"); info = getTransactionInfo(qryTrans.value(fieldId).toULongLong()); result.append(info); //qDebug()<<"APPENDING: id:"<<info.id<<" "<<info.date; } //qDebug()<<"executed query:"<<qryTrans.executedQuery(); //qDebug()<<"Qry size:"<<qryTrans.size(); } return result; } QList<TransactionInfo> Azahar::getDayTransactions(int terminal) { QList<TransactionInfo> result; TransactionInfo info; QSqlQuery qryTrans(db); QDate today = QDate::currentDate(); //NOTE: in the next query, the state and type are hardcoded (not using the enums) because problems when preparing query. State 8 = OwnCreditCompletedPaymentPending qryTrans.prepare("SELECT id,time,paidwith,paymethod,amount,utility,totalTax from transactions where (date = :today) AND (terminalnum=:terminal) AND (type=1) AND (state=2 OR state=8 OR state=9) ORDER BY id ASC;"); qryTrans.bindValue("today", today.toString("yyyy-MM-dd")); qryTrans.bindValue(":terminal", terminal); //tCompleted=2, tSell=1. With a placeholder, the value is inserted as a string, and cause the query to fail. if (!qryTrans.exec() ) { int errNum = qryTrans.lastError().number(); QSqlError::ErrorType errType = qryTrans.lastError().type(); QString errStr = qryTrans.lastError().text(); QString details = i18n("Error #%1, Type:%2\n'%3'",QString::number(errNum), QString::number(errType),errStr); setError(details); } else { while (qryTrans.next()) { int fieldAmount = qryTrans.record().indexOf("amount"); int fieldProfit = qryTrans.record().indexOf("utility"); info.id = qryTrans.value(qryTrans.record().indexOf("id")).toULongLong(); info.amount = qryTrans.value(fieldAmount).toDouble(); info.utility = qryTrans.value(fieldProfit).toDouble(); info.paymethod = qryTrans.value(qryTrans.record().indexOf("paymethod")).toInt(); info.paywith = qryTrans.value(qryTrans.record().indexOf("paidwith")).toDouble(); info.time = qryTrans.value(qryTrans.record().indexOf("time")).toTime(); info.totalTax = qryTrans.value(qryTrans.record().indexOf("totalTax")).toDouble(); result.append(info); //qDebug()<<"APPENDING:"<<info.id<< " Sales:"<<info.amount<<" Profit:"<<info.utility; } //qDebug()<<"executed query:"<<qryTrans.executedQuery(); //qDebug()<<"Qry size:"<<qryTrans.size(); } return result; } QList<TransactionInfo> Azahar::getDayTransactions() { QList<TransactionInfo> result; TransactionInfo info; QSqlQuery qryTrans(db); QDate today = QDate::currentDate(); //NOTE: in the next query, the state and type are hardcoded (not using the enums) because problems when preparing query. qryTrans.prepare("SELECT id,time,paidwith,paymethod,amount,utility,totalTax from transactions where (date = :today) AND (type=1) AND (state=2 OR state=8 OR state=9) ORDER BY id ASC;"); qryTrans.bindValue("today", today.toString("yyyy-MM-dd")); //tCompleted=2, tSell=1. With a placeholder, the value is inserted as a string, and cause the query to fail. if (!qryTrans.exec() ) { int errNum = qryTrans.lastError().number(); QSqlError::ErrorType errType = qryTrans.lastError().type(); QString errStr = qryTrans.lastError().text(); QString details = i18n("Error #%1, Type:%2\n'%3'",QString::number(errNum), QString::number(errType),errStr); setError(details); } else { while (qryTrans.next()) { int fieldAmount = qryTrans.record().indexOf("amount"); int fieldProfit = qryTrans.record().indexOf("utility"); info.id = qryTrans.value(qryTrans.record().indexOf("id")).toULongLong(); info.amount = qryTrans.value(fieldAmount).toDouble(); info.utility = qryTrans.value(fieldProfit).toDouble(); info.paymethod = qryTrans.value(qryTrans.record().indexOf("paymethod")).toInt(); info.paywith = qryTrans.value(qryTrans.record().indexOf("paidwith")).toDouble(); info.time = qryTrans.value(qryTrans.record().indexOf("time")).toTime(); info.totalTax = qryTrans.value(qryTrans.record().indexOf("totalTax")).toDouble(); result.append(info); //qDebug()<<"APPENDING:"<<info.id<< " Sales:"<<info.amount<<" Profit:"<<info.utility; } //qDebug()<<"executed query:"<<qryTrans.executedQuery(); //qDebug()<<"Qry size:"<<qryTrans.size(); } return result; } AmountAndProfitInfo Azahar::getDaySalesAndProfit(int terminal) { AmountAndProfitInfo result; QSqlQuery qryTrans(db); QDate today = QDate::currentDate(); //NOTE: in the next query, the state and type are hardcoded (not using the enums) because problems when preparing query. qryTrans.prepare("SELECT SUM(amount),SUM(utility) from transactions where (date = :today) AND (terminalnum=:terminal) AND (type=1) AND (state=2 OR state=8 OR state=9) GROUP BY date ASC;"); qryTrans.bindValue("today", today.toString("yyyy-MM-dd")); qryTrans.bindValue(":terminal", terminal); //tCompleted=2, tSell=1. With a placeholder, the value is inserted as a string, and cause the query to fail. if (!qryTrans.exec() ) { int errNum = qryTrans.lastError().number(); QSqlError::ErrorType errType = qryTrans.lastError().type(); QString errStr = qryTrans.lastError().text(); QString details = i18n("Error #%1, Type:%2\n'%3'",QString::number(errNum), QString::number(errType),errStr); setError(details); } else { while (qryTrans.next()) { int fieldAmount = qryTrans.record().indexOf("SUM(amount)"); int fieldProfit = qryTrans.record().indexOf("SUM(utility)"); result.amount = qryTrans.value(fieldAmount).toDouble(); result.profit = qryTrans.value(fieldProfit).toDouble(); //qDebug()<<"APPENDING:"<<info.date<< " Sales:"<<info.amount<<" Profit:"<<info.utility; } //qDebug()<<"executed query:"<<qryTrans.executedQuery(); //qDebug()<<"Qry size:"<<qryTrans.size(); } return result; } AmountAndProfitInfo Azahar::getDaySalesAndProfit() { AmountAndProfitInfo result; QSqlQuery qryTrans(db); QDate today = QDate::currentDate(); //NOTE: in the next query, the state and type are hardcoded (not using the enums) because problems when preparing query. qryTrans.prepare("SELECT SUM(amount),SUM(utility) from transactions where (date = :today) AND (type=1) AND (state=2 OR state=8 OR state=9) GROUP BY date ASC;"); qryTrans.bindValue("today", today.toString("yyyy-MM-dd")); //tCompleted=2, tSell=1. With a placeholder, the value is inserted as a string, and cause the query to fail. if (!qryTrans.exec() ) { int errNum = qryTrans.lastError().number(); QSqlError::ErrorType errType = qryTrans.lastError().type(); QString errStr = qryTrans.lastError().text(); QString details = i18n("Error #%1, Type:%2\n'%3'",QString::number(errNum), QString::number(errType),errStr); setError(details); } else { while (qryTrans.next()) { int fieldAmount = qryTrans.record().indexOf("SUM(amount)"); int fieldProfit = qryTrans.record().indexOf("SUM(utility)"); result.amount = qryTrans.value(fieldAmount).toDouble(); result.profit = qryTrans.value(fieldProfit).toDouble(); //qDebug()<<"APPENDING:"<<info.date<< " Sales:"<<info.amount<<" Profit:"<<info.utility; } //qDebug()<<"executed query:"<<qryTrans.executedQuery(); //qDebug()<<"Qry size:"<<qryTrans.size(); } return result; } //this returns the sales and profit from the 1st day of the month until today AmountAndProfitInfo Azahar::getMonthSalesAndProfit() { AmountAndProfitInfo result; QSqlQuery qryTrans(db); QDate today = QDate::currentDate(); QDate startDate = QDate(today.year(), today.month(), 1); //get the 1st of the month. //NOTE: in the next query, the state and type are hardcoded (not using the enums) because problems when preparing query. qryTrans.prepare("SELECT date,SUM(amount),SUM(utility) from transactions where (date BETWEEN :dateSTART AND :dateEND) AND (type=1) AND (state=2 OR state=8 OR state=9) GROUP BY type ASC;"); //group by type is to get the sum of all trans qryTrans.bindValue("dateSTART", startDate.toString("yyyy-MM-dd")); qryTrans.bindValue("dateEND", today.toString("yyyy-MM-dd")); //tCompleted=2, tSell=1. With a placeholder, the value is inserted as a string, and cause the query to fail. if (!qryTrans.exec() ) { int errNum = qryTrans.lastError().number(); QSqlError::ErrorType errType = qryTrans.lastError().type(); QString errStr = qryTrans.lastError().text(); QString details = i18n("Error #%1, Type:%2\n'%3'",QString::number(errNum), QString::number(errType),errStr); setError(details); } else { while (qryTrans.next()) { int fieldAmount = qryTrans.record().indexOf("SUM(amount)"); int fieldProfit = qryTrans.record().indexOf("SUM(utility)"); result.amount = qryTrans.value(fieldAmount).toDouble(); result.profit = qryTrans.value(fieldProfit).toDouble(); //qDebug()<<"APPENDING -- Sales:"<<result.amount<<" Profit:"<<result.profit; } //qDebug()<<"executed query:"<<qryTrans.executedQuery(); //qDebug()<<"Qry size:"<<qryTrans.size(); } return result; } //TRANSACTIONS qulonglong Azahar::insertTransaction(TransactionInfo info) { qulonglong result=0; //NOTE:The next commented code was deprecated because it will cause to overwrite transactions // When two or more terminals were getting an empty transacion at the same time, getting the same one. //first look for an empty transaction. //qulonglong availableId = getEmptyTransactionId(); //if (availableId > 0 ) { // qDebug()<<"The empty transaction # "<<availableId <<" is available to reuse."; // info.id = availableId; // if (updateTransaction(info)) result = availableId; //} //else { // insert a new one. QSqlQuery query2(db); query2.prepare("INSERT INTO transactions (clientid, type, amount, date, time, paidwith, changegiven, paymethod, state, userid, cardnumber, itemcount, itemslist, cardauthnumber, utility, terminalnum, providerid, specialOrders, balanceId, totalTax, cardtype) VALUES (:clientid, :type, :amount, :date, :time, :paidwith, :changegiven, :paymethod, :state, :userid, :cardnumber, :itemcount, :itemslist, :cardauthnumber, :utility, :terminalnum, :providerid, :specialOrders, :balance, :tax, :cardType)"); //removed groups 29DIC09 /** Remember to improve queries readability: * query2.prepare("INSERT INTO transactions ( \ clientid, userid, type, amount, date, time, \ paidwith, paymethod, changegiven, state, \ cardnumber, itemcount, itemslist, points, \ discmoney, disc, discmoney, cardauthnumber, profit, \ terminalnum, providerid, specialOrders, balanceId, totalTax) \ VALUES ( \ :clientid, :userid, :type, :amount, :date, :time, \ :paidwith, :paymethod, :changegiven, :state, \ :cardnumber, :itemcount, :itemslist, :points, \ :discmoney, :disc, :discm, :cardauthnumber, :utility, \ :terminalnum, :providerid, :specialOrders, :balanceId, :totalTax)"); **/ query2.bindValue(":type", info.type); query2.bindValue(":amount", info.amount); query2.bindValue(":date", info.date.toString("yyyy-MM-dd")); query2.bindValue(":time", info.time.toString("hh:mm")); query2.bindValue(":paidwith", info.paywith ); query2.bindValue(":changegiven", info.changegiven); query2.bindValue(":paymethod", info.paymethod); query2.bindValue(":state", info.state); query2.bindValue(":userid", info.userid); query2.bindValue(":clientid", info.clientid); query2.bindValue(":cardnumber", info.cardnumber); //.replace(0,15,"***************")); //FIXED: Only save last 4 digits query2.bindValue(":itemcount", info.itemcount); query2.bindValue(":itemslist", info.itemlist); query2.bindValue(":cardauthnumber", info.cardauthnum); query2.bindValue(":utility", info.utility); query2.bindValue(":terminalnum", info.terminalnum); query2.bindValue(":providerid", info.providerid); query2.bindValue(":tax", info.totalTax); query2.bindValue(":specialOrders", info.specialOrders); query2.bindValue(":balance", info.balanceId); query2.bindValue(":cardType", info.cardType); if (!query2.exec() ) { int errNum = query2.lastError().number(); QSqlError::ErrorType errType = query2.lastError().type(); QString errStr = query2.lastError().text(); QString details = i18n("Error #%1, Type:%2\n'%3'",QString::number(errNum), QString::number(errType),errStr); setError(details); } else result=query2.lastInsertId().toULongLong(); //} return result; } bool Azahar::updateTransaction(TransactionInfo info) { bool result=false; QSqlQuery query2(db); query2.prepare("UPDATE transactions SET disc=:disc, discmoney=:discMoney, amount=:amount, date=:date, time=:time, paidwith=:paidw, changegiven=:change, paymethod=:paymethod, cardtype=:cardType, state=:state, cardnumber=:cardnumber, itemcount=:itemcount, itemslist=:itemlist, cardauthnumber=:cardauthnumber, utility=:utility, terminalnum=:terminalnum, points=:points, clientid=:clientid, specialOrders=:sorders, balanceId=:balance, totalTax=:tax WHERE id=:code"); query2.bindValue(":disc", info.disc); query2.bindValue(":discMoney", info.discmoney); query2.bindValue(":code", info.id); query2.bindValue(":amount", info.amount); query2.bindValue(":date", info.date.toString("yyyy-MM-dd")); query2.bindValue(":time", info.time.toString("hh:mm")); query2.bindValue(":paidw", info.paywith ); query2.bindValue(":change", info.changegiven); query2.bindValue(":paymethod", info.paymethod); query2.bindValue(":state", info.state); query2.bindValue(":cardnumber", info.cardnumber);//.replace(0,15,"***************")); //FIXED: Only save last 4 digits query2.bindValue(":itemcount", info.itemcount); query2.bindValue(":itemlist", info.itemlist); query2.bindValue(":cardauthnumber", info.cardauthnum); query2.bindValue(":utility", info.utility); query2.bindValue(":terminalnum", info.terminalnum); query2.bindValue(":points", info.points); query2.bindValue(":clientid", info.clientid); query2.bindValue(":tax", info.totalTax); query2.bindValue(":sorders", info.specialOrders); query2.bindValue(":balance", info.balanceId); query2.bindValue(":cardType", info.cardType); qDebug()<<"Transaction ID:"<<info.id; if (!query2.exec() ) { int errNum = query2.lastError().number(); QSqlError::ErrorType errType = query2.lastError().type(); QString errStr = query2.lastError().text(); QString details = i18n("Error #%1, Type:%2\n'%3'",QString::number(errNum), QString::number(errType),errStr); setError(details); qDebug()<<"DETALLES DEL ERROR:"<<details; } else result=true; return result; } bool Azahar::deleteTransaction(qulonglong id) { bool result=false; if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery query(db); QString qry = QString("DELETE FROM transactions WHERE id=%1").arg(id); if (!query.exec(qry)) { result = false; int errNum = query.lastError().number(); QSqlError::ErrorType errType = query.lastError().type(); QString errStr = query.lastError().text(); QString details = i18n("Error #%1, Type:%2\n'%3'",QString::number(errNum), QString::number(errType),errStr); setError(details); } else { result = true; } } return result; } //NOTE: Is it convenient to reuse empty transactions or simply delete them? bool Azahar::deleteEmptyTransactions() { bool result = false; if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery query(db); QString qry = QString("DELETE FROM transactions WHERE itemcount<=0 and amount<=0"); if (!query.exec(qry)) { int errNum = query.lastError().number(); QSqlError::ErrorType errType = query.lastError().type(); QString errStr = query.lastError().text(); QString details = i18n("Error #%1, Type:%2\n'%3'",QString::number(errNum), QString::number(errType),errStr); setError(details); } else { result = true; } } return result; } qulonglong Azahar::getEmptyTransactionId() { qulonglong result = 0; if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery query(db); QString qry = QString("SELECT id from transactions WHERE itemcount<=0 and amount<=0"); if (!query.exec(qry)) { int errNum = query.lastError().number(); QSqlError::ErrorType errType = query.lastError().type(); QString errStr = query.lastError().text(); QString details = i18n("Error #%1, Type:%2\n'%3'",QString::number(errNum), QString::number(errType),errStr); setError(details); } else { while (query.next()) { int fieldId = query.record().indexOf("id"); result = query.value(fieldId).toULongLong(); return result; } } } return result; } bool Azahar::cancelTransaction(qulonglong id, bool inProgress) { bool result=false; if (!db.isOpen()) db.open(); bool ok = db.isOpen(); TransactionInfo tinfo = getTransactionInfo(id); bool transCompleted = false; bool alreadyCancelled = false; bool transExists = false; if (tinfo.id > 0) transExists = true; if (tinfo.state == tCompleted && transExists) transCompleted = true; if (tinfo.state == tCancelled && transExists) alreadyCancelled = true; ///TODO & FIXME: What about card payments? Return money or what to do? if (ok) { QSqlQuery query(db); QString qry; if (!inProgress && !alreadyCancelled && transExists) { qry = QString("UPDATE transactions SET state=%1 WHERE id=%2") .arg(tCancelled) .arg(id); if (!query.exec(qry)) { int errNum = query.lastError().number(); QSqlError::ErrorType errType = query.lastError().type(); QString errStr = query.lastError().text(); QString details = i18n("Error #%1, Type:%2\n'%3'",QString::number(errNum), QString::number(errType),errStr); setError(details); } else { //Cancelled... result = true; qDebug()<<"Marked as Cancelled!"; } ///not in progress, it means stockqty,points... are affected. if (transCompleted) { if (tinfo.points >0) decrementClientPoints(tinfo.clientid,tinfo.points); //TODO: when cancelling a transacion, take into account the groups sold to be returned. new feature QStringList soProducts; ///if there is any special order (product) if ( !tinfo.specialOrders.isEmpty() ) { //get each special order QStringList pSoList = tinfo.specialOrders.split(","); for (int i = 0; i < pSoList.size(); ++i) { QStringList l = pSoList.at(i).split("/"); if ( l.count()==2 ) { //==2 means its complete, having product and qty qulonglong soid = l.at(0).toULongLong(); //set as cancelled specialOrderSetStatus(soid, 4); //4 == cancelled //get each product of the special order to increment its stock later soProducts.append( getSpecialOrderProductsStr(soid) ); //are normal products (raw or not) } //if count } //for }//if there are special orders QString soProductsStr = soProducts.join(","); ///increment stock for each product. including special orders and groups QStringList plist = (tinfo.itemlist.split(",") + soProductsStr.split(",")); qDebug()<<"[*****] plist: "<< plist; for (int i = 0; i < plist.size(); ++i) { QStringList l = plist.at(i).split("/"); if ( l.count()==2 ) { //==2 means its complete, having product and qty //check if the product is a group //NOTE: rawProducts ? affect stock when cancelling = YES but only if affected when sold one of its parents (specialOrders) and stockqty is set. But they would not be here, if not at specialOrders List ProductInfo pi = getProductInfo(l.at(0)); if ( pi.isAGroup ) incrementGroupStock(l.at(0).toULongLong(), l.at(1).toDouble()); //code at 0, qty at 1 else //there is a normal product incrementProductStock(l.at(0).toULongLong(), l.at(1).toDouble()); //code at 0, qty at 1 } }//for each product ///save cashout for the money return qDebug()<<"Saving cashout-cancel"; CashFlowInfo cinfo; cinfo.userid = tinfo.userid; cinfo.amount = tinfo.amount; cinfo.date = QDate::currentDate(); cinfo.time = QTime::currentTime(); cinfo.terminalNum = tinfo.terminalnum; cinfo.type = ctCashOutMoneyReturnOnCancel; cinfo.reason = i18n("Money return on cancelling ticket #%1 ", id); insertCashFlow(cinfo); }//transCompleted } //not in progress } if ( alreadyCancelled ) { //The transaction was already canceled setError(i18n("Ticket #%1 was already canceled.", id)); result = false; qDebug()<<"Transaction already cancelled..."; } return result; } QList<TransactionInfo> Azahar::getLastTransactions(int pageNumber,int numItems,QDate beforeDate) { QList<TransactionInfo> result; result.clear(); QSqlQuery query(db); QString qry; qry = QString("SELECT * from transactions where type=1 and date <= STR_TO_DATE('%1', '%d/%m/%Y') order by date desc, id desc LIMIT %2,%3").arg(beforeDate.toString("dd/MM/yyyy")).arg((pageNumber-1)*numItems+1).arg(numItems); if (query.exec(qry)) { while (query.next()) { TransactionInfo info; int fieldId = query.record().indexOf("id"); int fieldAmount = query.record().indexOf("amount"); int fieldDate = query.record().indexOf("date"); int fieldTime = query.record().indexOf("time"); int fieldPaidWith = query.record().indexOf("paidwith"); int fieldPayMethod = query.record().indexOf("paymethod"); int fieldType = query.record().indexOf("type"); int fieldChange = query.record().indexOf("changegiven"); int fieldState = query.record().indexOf("state"); int fieldUserId = query.record().indexOf("userid"); int fieldClientId = query.record().indexOf("clientid"); int fieldCardNum = query.record().indexOf("cardnumber"); int fieldCardAuth = query.record().indexOf("cardauthnumber"); int fieldItemCount = query.record().indexOf("itemcount"); int fieldItemsList = query.record().indexOf("itemsList"); int fieldDiscount = query.record().indexOf("disc"); int fieldDiscMoney = query.record().indexOf("discmoney"); int fieldPoints = query.record().indexOf("points"); int fieldUtility = query.record().indexOf("utility"); int fieldTerminal = query.record().indexOf("terminalnum"); int fieldTax = query.record().indexOf("totalTax"); int fieldSOrd = query.record().indexOf("specialOrders"); int fieldBalance = query.record().indexOf("balanceId"); int fieldCardType = query.record().indexOf("cardtype"); info.id = query.value(fieldId).toULongLong(); info.amount = query.value(fieldAmount).toDouble(); info.date = query.value(fieldDate).toDate(); info.time = query.value(fieldTime).toTime(); info.paywith= query.value(fieldPaidWith).toDouble(); info.paymethod = query.value(fieldPayMethod).toInt(); info.type = query.value(fieldType).toInt(); info.changegiven = query.value(fieldChange).toDouble(); info.state = query.value(fieldState).toInt(); info.userid = query.value(fieldUserId).toULongLong(); info.clientid = query.value(fieldClientId).toULongLong(); info.cardnumber= query.value(fieldCardNum).toString();//.replace(0,15,"***************"); //FIXED: Only save last 4 digits; info.cardauthnum=query.value(fieldCardAuth).toString(); info.itemcount = query.value(fieldItemCount).toInt(); info.itemlist = query.value(fieldItemsList).toString(); info.disc = query.value(fieldDiscount).toDouble(); info.discmoney = query.value(fieldDiscMoney).toDouble(); info.points = query.value(fieldPoints).toULongLong(); info.utility = query.value(fieldUtility).toDouble(); info.terminalnum=query.value(fieldTerminal).toInt(); info.totalTax = query.value(fieldTax).toDouble(); info.specialOrders = query.value(fieldSOrd).toString(); info.balanceId = query.value(fieldBalance).toULongLong(); info.cardType = query.value(fieldCardType).toInt(); info.cardTypeStr = getCardTypeStr(info.cardType); result.append(info); } } else { setError(query.lastError().text()); } return result; } //NOTE: The next method is not used... Also, for what pourpose? is it missing the STATE condition? QList<TransactionInfo> Azahar::getTransactionsPerDay(int pageNumber,int numItems, QDate beforeDate) { QList<TransactionInfo> result; result.clear(); QSqlQuery query(db); QString qry; qry = QString("SELECT date, count(1) as transactions, sum(itemcount) as itemcount, sum(amount) as amount FROM transactions WHERE TYPE =1 AND date <= STR_TO_DATE('%1', '%d/%m/%Y') GROUP BY date(DATE) ORDER BY date DESC LIMIT %2,%3").arg(beforeDate.toString("dd/MM/yyyy")).arg((pageNumber-1)*numItems+1).arg(numItems); if (query.exec(qry)) { while (query.next()) { TransactionInfo info; int fieldTransactions = query.record().indexOf("transactions"); int fieldAmount = query.record().indexOf("amount"); int fieldDate = query.record().indexOf("date"); int fieldItemCount = query.record().indexOf("itemcount"); info.amount = query.value(fieldAmount).toDouble(); info.date = query.value(fieldDate).toDate(); info.state = query.value(fieldTransactions).toInt(); info.itemcount = query.value(fieldItemCount).toInt(); result.append(info); } } else { setError(query.lastError().text()); } return result; } double Azahar::getTransactionDiscMoney(qulonglong id) { double result = 0; QSqlQuery query(db); QString qry; qry = QString("SELECT discMoney FROM transactions WHERE id=%1").arg(id); if (query.exec(qry)) { while (query.next()) { int fieldAmount = query.record().indexOf("discMoney"); result = query.value(fieldAmount).toDouble(); } } else { setError(query.lastError().text()); } return result; } bool Azahar::setTransactionStatus(qulonglong trId, TransactionState state) { bool result = false; if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery query(db); if (state == tReserved) query.prepare("UPDATE transactions SET transactions.state=:state, transactions.totalTax=0 WHERE transactions.id=:trid"); else query.prepare("UPDATE transactions SET transactions.state=:state WHERE transactions.id=:trid"); query.bindValue(":trid", trId); query.bindValue(":state", state); qDebug()<< __FUNCTION__ << "Tr Id:"<<trId<<" State:"<<state; if (!query.exec() ) { int errNum = query.lastError().number(); QSqlError::ErrorType errType = query.lastError().type(); QString errStr = query.lastError().text(); QString details = i18n("Error #%1, Type:%2\n'%3'",QString::number(errNum), QString::number(errType),errStr); setError(details); } else result = true; } return result; } // TRANSACTIONITEMS bool Azahar::insertTransactionItem(TransactionItemInfo info) { bool result = false; if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery query(db); query.prepare("INSERT INTO transactionitems (transaction_id, position, product_id, qty, points, unitstr, cost, price, disc, total, name, payment, completePayment, soId, isGroup, deliveryDateTime, tax) VALUES(:transactionid, :position, :productCode, :qty, :points, :unitStr, :cost, :price, :disc, :total, :name, :payment, :completeP, :soid, :isGroup, :deliveryDT, :tax)"); query.bindValue(":transactionid", info.transactionid); query.bindValue(":position", info.position); query.bindValue(":productCode", info.productCode); query.bindValue(":qty", info.qty); query.bindValue(":points", info.points); query.bindValue(":unitStr", info.unitStr); query.bindValue(":cost", info.cost); query.bindValue(":price", info.price); query.bindValue(":disc", info.disc); query.bindValue(":total", info.total); query.bindValue(":name", info.name); query.bindValue(":payment", info.payment); query.bindValue(":completeP", info.completePayment); query.bindValue(":soid", info.soId); query.bindValue(":isGroup", info.isGroup); query.bindValue(":deliveryDT", info.deliveryDateTime); query.bindValue(":tax", info.tax); if (!query.exec()) { setError(query.lastError().text()); qDebug()<<"Insert TransactionItems error:"<<query.lastError().text(); } else result = true; } return result; } bool Azahar::deleteAllTransactionItem(qulonglong id) { bool result=false; if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery query(db); QString qry = QString("DELETE FROM transactionitems WHERE transaction_id=%1").arg(id); if (!query.exec(qry)) { result = false; int errNum = query.lastError().number(); QSqlError::ErrorType errType = query.lastError().type(); QString errStr = query.lastError().text(); QString details = i18n("Error #%1, Type:%2\n'%3'",QString::number(errNum), QString::number(errType),errStr); setError(details); } else { result = true; } } return result; } QList<TransactionItemInfo> Azahar::getTransactionItems(qulonglong id) { QList<TransactionItemInfo> result; result.clear(); QSqlQuery query(db); QString qry = QString("SELECT * FROM transactionitems WHERE transaction_id=%1 ORDER BY POSITION").arg(id); if (query.exec(qry)) { while (query.next()) { TransactionItemInfo info; int fieldPosition = query.record().indexOf("position"); int fieldProductCode = query.record().indexOf("product_id"); int fieldQty = query.record().indexOf("qty"); int fieldPoints = query.record().indexOf("points"); int fieldCost = query.record().indexOf("cost"); int fieldPrice = query.record().indexOf("price"); int fieldDisc = query.record().indexOf("disc"); int fieldTotal = query.record().indexOf("total"); int fieldName = query.record().indexOf("name"); int fieldUStr = query.record().indexOf("unitstr"); int fieldPayment = query.record().indexOf("payment"); int fieldCPayment = query.record().indexOf("completePayment"); int fieldSoid = query.record().indexOf("soId"); int fieldIsG = query.record().indexOf("isGroup"); int fieldDDT = query.record().indexOf("deliveryDateTime"); int fieldTax = query.record().indexOf("tax"); info.transactionid = id; info.position = query.value(fieldPosition).toInt(); info.productCode = query.value(fieldProductCode).toULongLong(); info.qty = query.value(fieldQty).toDouble(); info.points = query.value(fieldPoints).toDouble(); info.unitStr = query.value(fieldUStr).toString(); info.cost = query.value(fieldCost).toDouble(); info.price = query.value(fieldPrice).toDouble(); info.disc = query.value(fieldDisc).toDouble(); info.total = query.value(fieldTotal).toDouble(); info.name = query.value(fieldName).toString(); info.payment = query.value(fieldPayment).toDouble(); info.completePayment = query.value(fieldCPayment).toBool(); info.soId = query.value(fieldSoid).toString(); info.isGroup = query.value(fieldIsG).toBool(); info.deliveryDateTime=query.value(fieldDDT).toDateTime(); info.tax = query.value(fieldTax).toDouble(); result.append(info); } } else { setError(query.lastError().text()); qDebug()<<"Get TransactionItems error:"<<query.lastError().text(); } return result; } //BALANCES qulonglong Azahar::insertBalance(BalanceInfo info) { qulonglong result =0; if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery queryBalance(db); queryBalance.prepare("INSERT INTO balances (balances.datetime_start, balances.datetime_end, balances.userid, balances.usern, balances.initamount, balances.in, balances.out, balances.cash, balances.card, balances.transactions, balances.terminalnum, balances.cashflows, balances.done) VALUES (:date_start, :date_end, :userid, :user, :initA, :in, :out, :cash, :card, :transactions, :terminalNum, :cashflows, :isDone)"); queryBalance.bindValue(":date_start", info.dateTimeStart.toString("yyyy-MM-dd hh:mm:ss")); queryBalance.bindValue(":date_end", info.dateTimeEnd.toString("yyyy-MM-dd hh:mm:ss")); queryBalance.bindValue(":userid", info.userid); queryBalance.bindValue(":user", info.username); queryBalance.bindValue(":initA", info.initamount); queryBalance.bindValue(":in", info.in); queryBalance.bindValue(":out", info.out); queryBalance.bindValue(":cash", info.cash); queryBalance.bindValue(":card", info.card); queryBalance.bindValue(":transactions", info.transactions); queryBalance.bindValue(":terminalNum", info.terminal); queryBalance.bindValue(":cashflows", info.cashflows); queryBalance.bindValue(":isDone", info.done); if (!queryBalance.exec() ) { int errNum = queryBalance.lastError().number(); QSqlError::ErrorType errType = queryBalance.lastError().type(); QString errStr = queryBalance.lastError().text(); QString details = i18n("Error #%1, Type:%2\n'%3'",QString::number(errNum), QString::number(errType),errStr); setError(details); } else result = queryBalance.lastInsertId().toULongLong(); } return result; } BalanceInfo Azahar::getBalanceInfo(qulonglong id) { BalanceInfo info; info.id = 0; QString qry = QString("SELECT * FROM balances WHERE id=%1").arg(id); QSqlQuery query; if (!query.exec(qry)) { qDebug()<<query.lastError(); } else { while (query.next()) { int fieldId = query.record().indexOf("id"); int fieldDtStart = query.record().indexOf("datetime_start"); int fieldDtEnd = query.record().indexOf("datetime_end"); int fieldUserId = query.record().indexOf("userid"); int fieldUsername= query.record().indexOf("usern"); int fieldInitAmount = query.record().indexOf("initamount"); int fieldIn = query.record().indexOf("in"); int fieldOut = query.record().indexOf("out"); int fieldCash = query.record().indexOf("cash"); int fieldTransactions = query.record().indexOf("transactions"); int fieldCard = query.record().indexOf("card"); int fieldTerminalNum = query.record().indexOf("terminalnum"); int fieldCashFlows = query.record().indexOf("cashflows"); int fieldDone = query.record().indexOf("done"); info.id = query.value(fieldId).toULongLong(); info.dateTimeStart = query.value(fieldDtStart).toDateTime(); info.dateTimeEnd = query.value(fieldDtEnd).toDateTime(); info.userid = query.value(fieldUserId).toULongLong(); info.username= query.value(fieldUsername).toString(); info.initamount = query.value(fieldInitAmount).toDouble(); info.in = query.value(fieldIn).toDouble(); info.out = query.value(fieldOut).toDouble(); info.cash = query.value(fieldCash).toDouble(); info.card = query.value(fieldCard).toDouble(); info.transactions= query.value(fieldTransactions).toString(); info.terminal = query.value(fieldTerminalNum).toInt(); info.cashflows= query.value(fieldCashFlows).toString(); info.done = query.value(fieldDone).toBool(); } } return info; } bool Azahar::updateBalance(BalanceInfo info) { bool result = false; if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery queryBalance(db); queryBalance.prepare("UPDATE balances SET balances.datetime_start=:date_start, balances.datetime_end=:date_end, balances.userid=:userid, balances.usern=:user, balances.initamount=:initA, balances.in=:in, balances.out=:out, balances.cash=:cash, balances.card=:card, balances.transactions=:transactions, balances.terminalnum=:terminalNum, cashflows=:cashflows, done=:isDone WHERE balances.id=:bid"); queryBalance.bindValue(":date_start", info.dateTimeStart.toString("yyyy-MM-dd hh:mm:ss")); queryBalance.bindValue(":date_end", info.dateTimeEnd.toString("yyyy-MM-dd hh:mm:ss")); queryBalance.bindValue(":userid", info.userid); queryBalance.bindValue(":user", info.username); queryBalance.bindValue(":initA", info.initamount); queryBalance.bindValue(":in", info.in); queryBalance.bindValue(":out", info.out); queryBalance.bindValue(":cash", info.cash); queryBalance.bindValue(":card", info.card); queryBalance.bindValue(":transactions", info.transactions); queryBalance.bindValue(":terminalNum", info.terminal); queryBalance.bindValue(":cashflows", info.cashflows); queryBalance.bindValue(":bid", info.id); queryBalance.bindValue(":isDone", info.done); if (!queryBalance.exec() ) { int errNum = queryBalance.lastError().number(); QSqlError::ErrorType errType = queryBalance.lastError().type(); QString errStr = queryBalance.lastError().text(); QString details = i18n("Error #%1, Type:%2\n'%3'",QString::number(errNum), QString::number(errType),errStr); setError(details); } else result = true; } return result; } qulonglong Azahar::insertCashFlow(CashFlowInfo info) { qulonglong result =0; if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery query(db); query.prepare("INSERT INTO cashflow ( cashflow.userid, cashflow.type, cashflow.reason, cashflow.amount, cashflow.date, cashflow.time, cashflow.terminalnum) VALUES (:userid, :type, :reason, :amount, :date, :time, :terminalNum)"); query.bindValue(":date", info.date.toString("yyyy-MM-dd")); query.bindValue(":time", info.time.toString("hh:mm:ss")); query.bindValue(":userid", info.userid); query.bindValue(":terminalNum", info.terminalNum); query.bindValue(":reason", info.reason); query.bindValue(":amount", info.amount); query.bindValue(":type", info.type); if (!query.exec() ) { int errNum = query.lastError().number(); QSqlError::ErrorType errType = query.lastError().type(); QString errStr = query.lastError().text(); QString details = i18n("Error #%1, Type:%2\n'%3'",QString::number(errNum), QString::number(errType),errStr); setError(details); } else result = query.lastInsertId().toULongLong(); } return result; } QList<CashFlowInfo> Azahar::getCashFlowInfoList(const QList<qulonglong> &idList) { QList<CashFlowInfo> result; result.clear(); if (idList.count() == 0) return result; QSqlQuery query(db); foreach(qulonglong currId, idList) { QString qry = QString(" \ SELECT CF.id as id, \ CF.type as type, \ CF.userid as userid, \ CF.amount as amount, \ CF.reason as reason, \ CF.date as date, \ CF.time as time, \ CF.terminalNum as terminalNum, \ CFT.text as typeStr \ FROM cashflow AS CF, cashflowtypes AS CFT \ WHERE id=%1 AND (CFT.typeid = CF.type) ORDER BY CF.id;").arg(currId); if (query.exec(qry)) { while (query.next()) { CashFlowInfo info; int fieldId = query.record().indexOf("id"); int fieldType = query.record().indexOf("type"); int fieldUserId = query.record().indexOf("userid"); int fieldAmount = query.record().indexOf("amount"); int fieldReason = query.record().indexOf("reason"); int fieldDate = query.record().indexOf("date"); int fieldTime = query.record().indexOf("time"); int fieldTermNum = query.record().indexOf("terminalNum"); int fieldTStr = query.record().indexOf("typeStr"); info.id = query.value(fieldId).toULongLong(); info.type = query.value(fieldType).toULongLong(); info.userid = query.value(fieldUserId).toULongLong(); info.amount = query.value(fieldAmount).toDouble(); info.reason = query.value(fieldReason).toString(); info.typeStr = query.value(fieldTStr).toString(); info.date = query.value(fieldDate).toDate(); info.time = query.value(fieldTime).toTime(); info.terminalNum = query.value(fieldTermNum).toULongLong(); result.append(info); qDebug()<<__FUNCTION__<<" Cash Flow:"<<info.id<<" type:"<<info.type<<" reason:"<<info.reason; } } else { setError(query.lastError().text()); } } //foreach return result; } QList<CashFlowInfo> Azahar::getCashFlowInfoList(const QDateTime &start, const QDateTime &end) { QList<CashFlowInfo> result; result.clear(); QSqlQuery query(db); query.prepare(" \ SELECT CF.id as id, \ CF.type as type, \ CF.userid as userid, \ CF.amount as amount, \ CF.reason as reason, \ CF.date as date, \ CF.time as time, \ CF.terminalNum as terminalNum, \ CFT.text as typeStr \ FROM cashflow AS CF, cashflowtypes AS CFT \ WHERE (date BETWEEN :dateSTART AND :dateEND) AND (CFT.typeid = CF.type) ORDER BY CF.id"); query.bindValue(":dateSTART", start.date()); query.bindValue(":dateEND", end.date()); if (query.exec()) { while (query.next()) { QTime ttime = query.value(query.record().indexOf("time")).toTime(); if ( (ttime >= start.time()) && (ttime <= end.time()) ) { //its inside the requested time period. CashFlowInfo info; int fieldId = query.record().indexOf("id"); int fieldType = query.record().indexOf("type"); int fieldUserId = query.record().indexOf("userid"); int fieldAmount = query.record().indexOf("amount"); int fieldReason = query.record().indexOf("reason"); int fieldDate = query.record().indexOf("date"); int fieldTime = query.record().indexOf("time"); int fieldTermNum = query.record().indexOf("terminalNum"); int fieldTStr = query.record().indexOf("typeStr"); info.id = query.value(fieldId).toULongLong(); info.type = query.value(fieldType).toULongLong(); info.userid = query.value(fieldUserId).toULongLong(); info.amount = query.value(fieldAmount).toDouble(); info.reason = query.value(fieldReason).toString(); info.typeStr = query.value(fieldTStr).toString(); info.date = query.value(fieldDate).toDate(); info.time = query.value(fieldTime).toTime(); info.terminalNum = query.value(fieldTermNum).toULongLong(); result.append(info); } //if time... } //while }// if query else { setError(query.lastError().text()); } return result; } //Card Types QHash<QString, int> Azahar::getCardTypesHash() { QHash<QString, int> result; result.clear(); if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery myQuery(db); if (myQuery.exec("select * from cardtypes;")) { while (myQuery.next()) { int fieldId = myQuery.record().indexOf("typeid"); int fieldText = myQuery.record().indexOf("text"); int id = myQuery.value(fieldId).toInt(); QString text = myQuery.value(fieldText).toString(); result.insert(text, id); } } else { qDebug()<<"ERROR: "<<myQuery.lastError(); } } return result; } QStringList Azahar::getCardTypes() { QStringList result; QSqlQuery query(db); QString qstr = QString("select text from cardtypes;"); if (query.exec(qstr)) { while (query.next()) { int fieldText = query.record().indexOf("text"); result.append(query.value(fieldText).toString()); } } else { setError(query.lastError().text()); } return result; } QString Azahar::getCardTypeStr(qulonglong type) { QString result; QSqlQuery query(db); QString qstr = QString("select text from cardtypes where cardtypes.typeid=%1;").arg(type); if (query.exec(qstr)) { while (query.next()) { int fieldText = query.record().indexOf("text"); result = query.value(fieldText).toString(); } } else { setError(query.lastError().text()); } return result; } qulonglong Azahar::getCardTypeId(QString type) { qulonglong result=0; QSqlQuery query(db); QString qstr = QString("select typeid from cardtypes where cardtypes.text='%1';").arg(type); if (query.exec(qstr)) { while (query.next()) { int fieldText = query.record().indexOf("typeid"); result = query.value(fieldText).toULongLong(); } } else { setError(query.lastError().text()); } return result; } //TransactionTypes QString Azahar::getPayTypeStr(qulonglong type) { QString result; QSqlQuery query(db); QString qstr = QString("select text from paytypes where paytypes.typeid=%1;").arg(type); if (query.exec(qstr)) { while (query.next()) { int fieldText = query.record().indexOf("text"); result = query.value(fieldText).toString(); } } else { setError(query.lastError().text()); } return result; } qulonglong Azahar::getPayTypeId(QString type) { qulonglong result=0; QSqlQuery query(db); QString qstr = QString("select typeid from paytypes where paytypes.text='%1';").arg(type); if (query.exec(qstr)) { while (query.next()) { int fieldText = query.record().indexOf("typeid"); result = query.value(fieldText).toULongLong(); } } else { setError(query.lastError().text()); } return result; } //LOGS bool Azahar::insertLog(const qulonglong &userid, const QDate &date, const QTime &time, const QString actionStr) { bool result = false; if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery query(db); query.prepare("INSERT INTO logs (userid, date, time, action) VALUES(:userid, :date, :time, :action);"); query.bindValue(":userid", userid); query.bindValue(":date", date.toString("yyyy-MM-dd")); query.bindValue(":time", time.toString("hh:mm")); query.bindValue(":action", actionStr); if (!query.exec()) { setError(query.lastError().text()); qDebug()<<"ERROR ON SAVING LOG:"<<query.lastError().text(); } else result = true; } return result; } bool Azahar::getConfigFirstRun() { bool result = false; if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery myQuery(db); if (myQuery.exec(QString("select firstrun from config;"))) { while (myQuery.next()) { int fieldText = myQuery.record().indexOf("firstrun"); QString value = myQuery.value(fieldText).toString(); qDebug()<<"firstRun VALUE="<<value; if (value == "yes, it is February 6 1978") result = true; } } else { qDebug()<<"ERROR: "<<myQuery.lastError(); } } return result; } bool Azahar::getConfigTaxIsIncludedInPrice() { bool result = false; if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery myQuery(db); if (myQuery.exec(QString("select taxIsIncludedInPrice from config;"))) { while (myQuery.next()) { int fieldText = myQuery.record().indexOf("taxIsIncludedInPrice"); result = myQuery.value(fieldText).toBool(); } } else { qDebug()<<"ERROR: "<<myQuery.lastError(); } } return result; } void Azahar::cleanConfigFirstRun() { if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery myQuery(db); if (myQuery.exec(QString("update config set firstrun='yes, i like the rainy days';"))) { qDebug()<<"Change config firstRun..."; } else { qDebug()<<"ERROR: "<<myQuery.lastError(); } } } void Azahar::setConfigTaxIsIncludedInPrice(bool option) { if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery myQuery(db); if (myQuery.exec(QString("update config set taxIsIncludedInPrice=%1;").arg(option))) { qDebug()<<"Change config taxIsIncludedInPrice..."; } else { qDebug()<<"ERROR: "<<myQuery.lastError(); } } } QPixmap Azahar::getConfigStoreLogo() { QPixmap result; if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery myQuery(db); if (myQuery.exec(QString("select storeLogo from config;"))) { while (myQuery.next()) { int fieldText = myQuery.record().indexOf("storeLogo"); result.loadFromData(myQuery.value(fieldText).toByteArray()); } } else { qDebug()<<"ERROR: "<<myQuery.lastError(); } } return result; } QString Azahar::getConfigStoreName() { QString result; if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery myQuery(db); if (myQuery.exec(QString("select storeName from config;"))) { while (myQuery.next()) { int fieldText = myQuery.record().indexOf("storeName"); result = myQuery.value(fieldText).toString(); } } else { qDebug()<<"ERROR: "<<myQuery.lastError(); } } return result; } QString Azahar::getConfigStoreAddress() { QString result; if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery myQuery(db); if (myQuery.exec(QString("select storeAddress from config;"))) { while (myQuery.next()) { int fieldText = myQuery.record().indexOf("storeAddress"); result = myQuery.value(fieldText).toString(); } } else { qDebug()<<"ERROR: "<<myQuery.lastError(); } } return result; } QString Azahar::getConfigStorePhone() { QString result; if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery myQuery(db); if (myQuery.exec(QString("select storePhone from config;"))) { while (myQuery.next()) { int fieldText = myQuery.record().indexOf("storePhone"); result = myQuery.value(fieldText).toString(); } } else { qDebug()<<"ERROR: "<<myQuery.lastError(); } } return result; } bool Azahar::getConfigSmallPrint() { bool result = false; if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery myQuery(db); if (myQuery.exec(QString("select smallPrint from config;"))) { while (myQuery.next()) { int fieldText = myQuery.record().indexOf("smallPrint"); result = myQuery.value(fieldText).toBool(); } } else { qDebug()<<"ERROR: "<<myQuery.lastError(); } } return result; } bool Azahar::getConfigLogoOnTop() { bool result = false; if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery myQuery(db); if (myQuery.exec(QString("select logoOnTop from config;"))) { while (myQuery.next()) { int fieldText = myQuery.record().indexOf("logoOnTop"); result = myQuery.value(fieldText).toBool(); } } else { qDebug()<<"ERROR: "<<myQuery.lastError(); } } return result; } bool Azahar::getConfigUseCUPS() { bool result = false; if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery myQuery(db); if (myQuery.exec(QString("select useCUPS from config;"))) { while (myQuery.next()) { int fieldText = myQuery.record().indexOf("useCUPS"); result = myQuery.value(fieldText).toBool(); } } else { qDebug()<<"ERROR: "<<myQuery.lastError(); } } return result; } QString Azahar::getConfigDbVersion() { QString result = ""; if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery myQuery(db); if (myQuery.exec(QString("select db_version from config;"))) { while (myQuery.next()) { int fieldText = myQuery.record().indexOf("db_version"); result = myQuery.value(fieldText).toString(); } } else { qDebug()<<"ERROR: "<<myQuery.lastError(); } } return result; } void Azahar::setConfigStoreLogo(const QByteArray &baPhoto) { if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery myQuery(db); myQuery.prepare("update config set storeLogo=:logo;"); myQuery.bindValue(":logo", baPhoto); if (myQuery.exec()) { qDebug()<<"Change config store logo..."; } else { qDebug()<<"ERROR: "<<myQuery.lastError(); } } } void Azahar::setConfigStoreName(const QString &str) { if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery myQuery(db); if (myQuery.exec(QString("update config set storeName='%1';").arg(str))) { qDebug()<<"Change config storeName..."; } else { qDebug()<<"ERROR: "<<myQuery.lastError(); } } } void Azahar::setConfigStoreAddress(const QString &str) { if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery myQuery(db); if (myQuery.exec(QString("update config set storeAddress='%1';").arg(str))) { qDebug()<<"Change config storeAddress..."; } else { qDebug()<<"ERROR: "<<myQuery.lastError(); } } } void Azahar::setConfigStorePhone(const QString &str) { if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery myQuery(db); if (myQuery.exec(QString("update config set storePhone='%1';").arg(str))) { qDebug()<<"Change config taxIsIncludedInPrice..."; } else { qDebug()<<"ERROR: "<<myQuery.lastError(); } } } void Azahar::setConfigSmallPrint(bool yes) { if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery myQuery(db); if (myQuery.exec(QString("update config set smallPrint=%1;").arg(yes))) { qDebug()<<"Change config SmallPrint..."; } else { qDebug()<<"ERROR: "<<myQuery.lastError(); } } } void Azahar::setConfigUseCUPS(bool yes) { if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery myQuery(db); if (myQuery.exec(QString("update config set useCUPS=%1;").arg(yes))) { qDebug()<<"Change config useCUPS..."; } else { qDebug()<<"ERROR: "<<myQuery.lastError(); } } } void Azahar::setConfigLogoOnTop(bool yes) { if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery myQuery(db); if (myQuery.exec(QString("update config set logoOnTop=%1;").arg(yes))) { qDebug()<<"Change config logoOnTop..."; } else { qDebug()<<"ERROR: "<<myQuery.lastError(); } } } //SPECIAL ORDERS QList<SpecialOrderInfo> Azahar::getAllSOforSale(qulonglong saleId) { QList<SpecialOrderInfo> list; if (!db.isOpen()) db.open(); if (db.isOpen()) { QString qry = QString("SELECT orderid,saleid from special_orders where saleid=%1").arg(saleId); QSqlQuery query(db); if (!query.exec(qry)) { int errNum = query.lastError().number(); QSqlError::ErrorType errType = query.lastError().type(); QString error = query.lastError().text(); QString details = i18n("Error #%1, Type:%2\n'%3'",QString::number(errNum), QString::number(errType),error); setError(i18n("Error getting special Order information, id: %1, Rows affected: %2", saleId,query.size())); } else { while (query.next()) { int fieldId = query.record().indexOf("orderid"); qulonglong num = query.value(fieldId).toULongLong(); SpecialOrderInfo soInfo = getSpecialOrderInfo(num); list.append(soInfo); } } } return list; } //NOTE: Here the question is, what status to take into account? pending,inprogress,ready... // We will return all with status < 3 . QList<SpecialOrderInfo> Azahar::getAllReadySOforSale(qulonglong saleId) { QList<SpecialOrderInfo> list; if (!db.isOpen()) db.open(); if (db.isOpen()) { QString qry = QString("SELECT orderid,saleid from special_orders where saleid=%1 and status<3").arg(saleId); QSqlQuery query(db); if (!query.exec(qry)) { int errNum = query.lastError().number(); QSqlError::ErrorType errType = query.lastError().type(); QString error = query.lastError().text(); QString details = i18n("Error #%1, Type:%2\n'%3'",QString::number(errNum), QString::number(errType),error); setError(i18n("Error getting special Order information, id: %1, Rows affected: %2", saleId,query.size())); } else { while (query.next()) { int fieldId = query.record().indexOf("orderid"); qulonglong num = query.value(fieldId).toULongLong(); SpecialOrderInfo soInfo = getSpecialOrderInfo(num); list.append(soInfo); } } } return list; } int Azahar::getReadySOCountforSale(qulonglong saleId) { int count=0; if (!db.isOpen()) db.open(); if (db.isOpen()) { QString qry = QString("SELECT orderid from special_orders where saleid=%1 and status<3").arg(saleId); QSqlQuery query(db); if (!query.exec(qry)) { int errNum = query.lastError().number(); QSqlError::ErrorType errType = query.lastError().type(); QString error = query.lastError().text(); QString details = i18n("Error #%1, Type:%2\n'%3'",QString::number(errNum), QString::number(errType),error); setError(i18n("Error getting special Order information, id: %1, Rows affected: %2", saleId,query.size())); } else { // while (query.next()) { // count++; // } count = query.size(); } } return count; } void Azahar::specialOrderSetStatus(qulonglong id, int status) { if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery myQuery(db); if (myQuery.exec(QString("update special_orders set status=%1 where orderid=%2;").arg(status).arg(id))) { qDebug()<<"Status Order updated"; } else { qDebug()<<"ERROR: "<<myQuery.lastError(); } } } void Azahar::soTicketSetStatus(qulonglong ticketId, int status) { if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery myQuery(db); if (myQuery.exec(QString("update special_orders set status=%1 where saleid=%2;").arg(status).arg(ticketId))) { qDebug()<<"Status Order updated"; } else { qDebug()<<"ERROR: "<<myQuery.lastError(); } } } QString Azahar::getSpecialOrderProductsStr(qulonglong id) { QString result = ""; if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery myQuery(db); if (myQuery.exec(QString("select groupElements from special_orders where orderid=%1;").arg(id))) { while (myQuery.next()) { int fieldText = myQuery.record().indexOf("groupElements"); result = myQuery.value(fieldText).toString(); } } else { qDebug()<<"ERROR: "<<myQuery.lastError(); } } return result; } QList<ProductInfo> Azahar::getSpecialOrderProductsList(qulonglong id) { QList<ProductInfo> pList; if (!db.isOpen()) db.open(); if (db.isOpen()) { QString ge = getSpecialOrderProductsStr(id); QStringList pq = ge.split(","); foreach(QString str, pq) { qulonglong c = str.section('/',0,0).toULongLong(); double q = str.section('/',1,1).toDouble(); //get info ProductInfo pi = getProductInfo(QString::number(c)); pi.qtyOnList = q; pList.append(pi); } } return pList; } QString Azahar::getSONotes(qulonglong id) { QString result = ""; if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery myQuery(db); if (myQuery.exec(QString("select notes from special_orders where orderid=%1;").arg(id))) { while (myQuery.next()) { int fieldText = myQuery.record().indexOf("notes"); result = myQuery.value(fieldText).toString(); } } else { qDebug()<<"ERROR: "<<myQuery.lastError(); } } return result; } qulonglong Azahar::insertSpecialOrder(SpecialOrderInfo info) { qulonglong result = 0; if (!db.isOpen()) db.open(); QSqlQuery query(db); query.prepare("INSERT INTO special_orders (name, price, qty, cost, units, groupElements, status, saleid, notes, payment, completePayment, dateTime, deliveryDateTime,clientId,userId) VALUES (:name, :price, :qty, :cost, :units, :groupE, :status, :saleId, :notes, :payment, :completeP, :dateTime, :deliveryDT, :client, :user);"); query.bindValue(":name", info.name); query.bindValue(":price", info.price); query.bindValue(":qty", info.qty); query.bindValue(":cost", info.cost); query.bindValue(":status", info.status); query.bindValue(":units", info.units); query.bindValue(":groupE", info.groupElements); query.bindValue(":saleId", info.saleid); query.bindValue(":notes", info.notes); query.bindValue(":payment", info.payment); query.bindValue(":completeP", info.completePayment); query.bindValue(":dateTime", info.dateTime); query.bindValue(":deliveryDT", info.deliveryDateTime); query.bindValue(":user", info.userId); query.bindValue(":client", info.clientId); if (!query.exec()) setError(query.lastError().text()); else { result=query.lastInsertId().toULongLong(); } return result; } //saleid, dateTime/userid/clientid are not updated. bool Azahar::updateSpecialOrder(SpecialOrderInfo info) { bool result = false; if (!db.isOpen()) db.open(); QSqlQuery query(db); query.prepare("UPDATE special_orders SET name=:name, price=:price, qty=:qty, cost=:cost, units=:units, groupElements=:groupE, status=:status, notes=:notes, payment=:payment, completePayment=:completeP, deliveryDateTime=:deliveryDT WHERE orderid=:code;"); query.bindValue(":code", info.orderid); query.bindValue(":name", info.name); query.bindValue(":price", info.price); query.bindValue(":qty", info.qty); query.bindValue(":cost", info.cost); query.bindValue(":status", info.status); query.bindValue(":units", info.units); query.bindValue(":groupE", info.groupElements); query.bindValue(":notes", info.notes); query.bindValue(":payment", info.payment); query.bindValue(":completeP", info.completePayment); query.bindValue(":deliveryDT", info.deliveryDateTime); if (!query.exec()) setError(query.lastError().text()); else result=true; return result; } bool Azahar::decrementSOStock(qulonglong id, double qty, QDate date) { bool result = true; if (!db.isOpen()) db.open(); QSqlQuery query(db); QList<QString> lelem = getSpecialOrderProductsStr(id).split(","); foreach(QString ea, lelem) { qulonglong c = ea.section('/',0,0).toULongLong(); double q = ea.section('/',1,1).toDouble(); //FOR EACH ELEMENT, DECREMENT PRODUCT STOCK result = result && decrementProductStock(c, q*qty, date); } return result; } bool Azahar::deleteSpecialOrder(qulonglong id) { bool result = false; if (!db.isOpen()) db.open(); QSqlQuery query(db); query = QString("DELETE FROM special_orders WHERE orderid=%1").arg(id); if (!query.exec()) setError(query.lastError().text()); else result=true; return result; } SpecialOrderInfo Azahar::getSpecialOrderInfo(qulonglong id) { SpecialOrderInfo info; info.orderid=0; info.name="Ninguno"; info.price=0; if (!db.isOpen()) db.open(); if (db.isOpen()) { QString qry = QString("SELECT * from special_orders where orderid=%1").arg(id); QSqlQuery query(db); if (!query.exec(qry)) { int errNum = query.lastError().number(); QSqlError::ErrorType errType = query.lastError().type(); QString error = query.lastError().text(); QString details = i18n("Error #%1, Type:%2\n'%3'",QString::number(errNum), QString::number(errType),error); setError(i18n("Error getting special Order information, id: %1, Rows affected: %2", id,query.size())); } else { while (query.next()) { int fieldDesc = query.record().indexOf("name"); int fieldPrice= query.record().indexOf("price"); int fieldQty= query.record().indexOf("qty"); int fieldCost= query.record().indexOf("cost"); int fieldUnits= query.record().indexOf("units"); int fieldStatus= query.record().indexOf("status"); int fieldSaleId= query.record().indexOf("saleid"); int fieldGroupE = query.record().indexOf("groupElements"); int fieldPayment = query.record().indexOf("payment"); int fieldCPayment = query.record().indexOf("completePayment"); int fieldDateT = query.record().indexOf("dateTime"); int fieldDDT = query.record().indexOf("deliveryDateTime"); int fieldNotes = query.record().indexOf("notes"); int fieldClientId = query.record().indexOf("clientId"); int fieldUserId = query.record().indexOf("userId"); info.orderid=id; info.name = query.value(fieldDesc).toString(); info.price = query.value(fieldPrice).toDouble(); info.qty = query.value(fieldQty).toDouble(); info.cost = query.value(fieldCost).toDouble(); info.units = query.value(fieldUnits).toInt(); info.status = query.value(fieldStatus).toInt(); info.saleid = query.value(fieldSaleId).toULongLong(); info.groupElements = query.value(fieldGroupE).toString(); info.payment = query.value(fieldPayment).toDouble(); info.completePayment = query.value(fieldCPayment).toBool(); info.dateTime = query.value(fieldDateT).toDateTime(); info.deliveryDateTime = query.value(fieldDDT).toDateTime(); info.notes = query.value(fieldNotes).toString(); info.clientId = query.value(fieldClientId).toULongLong(); info.userId = query.value(fieldUserId).toULongLong(); //get specialOrder Discounts info.disc = getSpecialOrderAverageDiscount(info.orderid)/100; //in percentage. } //get units descriptions qry = QString("SELECT * from measures WHERE id=%1").arg(info.units); QSqlQuery query3(db); if (query3.exec(qry)) { while (query3.next()) { int fieldUD = query3.record().indexOf("text"); info.unitStr=query3.value(fieldUD).toString(); }//query3 - get descritptions } } } return info; } // NOTE: This returns the compound tax that effectively apply to the amount for the specialOrder, // regardless of the equitative tax for each product. It means that the tax returned is the // EFFECTIVE tax for the total amount, instead of an average tax (total/numberOfProducts).. // The average tax is not accurate if there are different products with very different taxes. // For example: // A SO with TWO products : // product 1: Price: 10, tax:15% // product 2: Price 100, tax 1% // The average tax is 8%, its equally for the two products but the second one has a lower tax. // The tax charged to the group with the average tax is $8.8 // The tax charged to the group with each product tax is $2.15 // This means the average tax is not accurate for all cases. // Thats why this 'effective' tax average is returned. double Azahar::getSpecialOrderAverageTax(qulonglong id, AzaharRTypes returnType) { double price = 0; double taxMoney = 0; double tax = 0; if ( id <= 0 ) return 0; QList<ProductInfo> pList = getSpecialOrderProductsList(id); foreach( ProductInfo info, pList) { double discount = 0; double pWOtax= 0; if (info.validDiscount) discount = info.price*info.qtyOnList*(info.discpercentage/100); if ( !getConfigTaxIsIncludedInPrice() ) pWOtax = info.price; else pWOtax= info.price/(1+((info.tax+info.extratax)/100)); price += (pWOtax*info.qtyOnList)-discount; taxMoney += (info.tax/100)*((info.qtyOnList*pWOtax)-discount); //info.totaltax*info.qtyOnList; //qDebug()<<" < EACH ONE > price: "<<(pWOtax*info.qtyOnList)-discount<<" taxMoney: "<<(info.tax/100)*((pWOtax*info.qtyOnList)-discount) //<<" Discount:"<<discount<<" pWOTax:"<<pWOtax; } foreach(ProductInfo info, pList) { tax += (info.totaltax*info.qtyOnList/price)*100; } qDebug()<<"\n <<<<<<< GetSpecialOrderAverageTax :%"<<tax<<" $"<<taxMoney<<" Based Price:"<<price<<">>>>>>>>\n"; if (returnType == rtMoney) return taxMoney; else return tax; } ///This gets discounts on a special order based on its raw products discount, returned in %. double Azahar::getSpecialOrderAverageDiscount(qulonglong id) { double price = 0; double discMoney = 0; double disc = 0; if ( id <= 0 ) return 0; QList<ProductInfo> pList = getSpecialOrderProductsList(id); foreach( ProductInfo info, pList) { price += info.price*info.qtyOnList; if (info.validDiscount && !info.isNotDiscountable) discMoney += (info.discpercentage/100)*info.price*info.qtyOnList; //qDebug()<<" < EACH ONE > price: "<<info.price*info.qtyOnList<<" discMoney: "<<(info.discpercentage/100)*info.price*info.qtyOnList; } foreach(ProductInfo info, pList) { if (info.validDiscount && !info.isNotDiscountable) disc += ( ((info.discpercentage/100)*info.price*info.qtyOnList)/price )*100; //qDebug()<<" < SO DISCOUNT > qtyOnList:"<<info.qtyOnList<<" discMoney for product: "<<(info.discpercentage/100)*info.price*info.qtyOnList<<" SO price:"<<price<<" discMoney for group:"<<discMoney<<" DISCOUNT % for group:"<< disc; } qDebug()<<"\n <<<<<<< GetSpecialOrderAverageDiscount :%"<<disc<<" $"<<discMoney<<" Based Price:"<<price<<">>>>>>>>\n"; return disc; } int Azahar::getSpecialOrderNonDiscountables(qulonglong id) { int count = 0; if ( id <= 0 ) return 0; QList<ProductInfo> pList = getSpecialOrderProductsList(id); foreach(ProductInfo info, pList) { if (info.isNotDiscountable) count++; } return count; } QStringList Azahar::getStatusList() { QStringList result; result.clear(); if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery myQuery(db); if (myQuery.exec("select text from so_status;")) { while (myQuery.next()) { int fieldText = myQuery.record().indexOf("text"); QString text = myQuery.value(fieldText).toString(); result.append(text); } } else { qDebug()<<"ERROR: "<<myQuery.lastError(); } } return result; } QStringList Azahar::getStatusListExceptDelivered() { QStringList result; result.clear(); if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery myQuery(db); if (myQuery.exec(QString("select text from so_status where id!=%1;").arg(stDelivered))) { while (myQuery.next()) { int fieldText = myQuery.record().indexOf("text"); QString text = myQuery.value(fieldText).toString(); result.append(text); } } else { qDebug()<<"ERROR: "<<myQuery.lastError(); } } return result; } int Azahar::getStatusId(QString texto) { qulonglong result=0; if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery myQuery(db); QString qryStr = QString("SELECT so_status.id FROM so_status WHERE text='%1';").arg(texto); if (myQuery.exec(qryStr) ) { while (myQuery.next()) { int fieldId = myQuery.record().indexOf("id"); qulonglong id= myQuery.value(fieldId).toULongLong(); result = id; } } else { setError(myQuery.lastError().text()); } } return result; } QString Azahar::getRandomMessage(QList<qulonglong> &excluded, const int &season) { QString result; QString firstMsg; qulonglong firstId = 0; if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery myQuery(db); QString qryStr = QString("SELECT message,id FROM random_msgs WHERE season=%1 order by count ASC;").arg(season); if (myQuery.exec(qryStr) ) { while (myQuery.next()) { int fieldId = myQuery.record().indexOf("id"); int fieldMsg = myQuery.record().indexOf("message"); qulonglong id = myQuery.value(fieldId).toULongLong(); if ( firstMsg.isEmpty() ) { firstMsg = myQuery.value(fieldMsg).toString(); //get the first msg. firstId = myQuery.value(fieldId).toULongLong(); } qDebug()<<"Examining msg Id: "<<id; //check if its not on the excluded list. if ( !excluded.contains(id) ) { //ok, return the msg, increment count. result = myQuery.value(fieldMsg).toString(); randomMsgIncrementCount(id); //modify the excluded list, insert this one. excluded.append(id); //we exit from the while loop. qDebug()<<" We got msg:"<<result; break; } } } else { setError(myQuery.lastError().text()); } } if (result.isEmpty() && firstId > 0) { result = firstMsg; randomMsgIncrementCount(firstId); excluded << firstId; qDebug()<<"Returning the fist message!"; } return result; } void Azahar::randomMsgIncrementCount(qulonglong id) { if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery myQuery(db); if (myQuery.exec(QString("update random_msgs set count=count+1 where id=%1;").arg(id))) { qDebug()<<"Random Messages Count updated"; } else { qDebug()<<"ERROR: "<<myQuery.lastError(); } } } bool Azahar::insertRandomMessage(const QString &msg, const int &season) { bool result = false; if (!db.isOpen()) db.open(); QSqlQuery query(db); query.prepare("INSERT INTO random_msgs (message, season, count) VALUES (:message, :season, :count);"); query.bindValue(":msg", msg); query.bindValue(":season", season); query.bindValue(":count", 0); if (!query.exec()) { setError(query.lastError().text()); } else result=true; return result; } CurrencyInfo Azahar::getCurrency(const qulonglong &id) { CurrencyInfo result; result.id = 0; if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery myQuery(db); if (myQuery.exec(QString("select * from currencies where id=%1;").arg(id))) { while (myQuery.next()) { int fieldName = myQuery.record().indexOf("name"); int fieldFactor = myQuery.record().indexOf("factor"); result.name = myQuery.value(fieldName).toString(); result.factor = myQuery.value(fieldFactor).toDouble(); result.id = id; } } else { qDebug()<<"ERROR: "<<myQuery.lastError(); } } return result; } CurrencyInfo Azahar::getCurrency(const QString &name) { CurrencyInfo result; result.id = 0; if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery myQuery(db); if (myQuery.exec(QString("select * from currencies where name='%1';").arg(name))) { while (myQuery.next()) { int fieldName = myQuery.record().indexOf("name"); int fieldFactor = myQuery.record().indexOf("factor"); int fieldId = myQuery.record().indexOf("id"); result.name = myQuery.value(fieldName).toString(); result.factor = myQuery.value(fieldFactor).toDouble(); result.id = myQuery.value(fieldId).toULongLong(); } } else { qDebug()<<"ERROR: "<<myQuery.lastError(); } } return result; } QList<CurrencyInfo> Azahar::getCurrencyList() { QList<CurrencyInfo> result; if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery myQuery(db); if (myQuery.exec(QString("select * from currencies;"))) { while (myQuery.next()) { CurrencyInfo info; int fieldName = myQuery.record().indexOf("name"); int fieldFactor = myQuery.record().indexOf("factor"); int fieldId = myQuery.record().indexOf("id"); info.name = myQuery.value(fieldName).toString(); info.factor = myQuery.value(fieldFactor).toDouble(); info.id = myQuery.value(fieldId).toULongLong(); result.append(info); } } else { qDebug()<<"ERROR: "<<myQuery.lastError(); } } return result; } bool Azahar::insertCurrency(const QString name, const double &factor) { bool result = false; if (!db.isOpen()) db.open(); QSqlQuery query(db); query.prepare("INSERT INTO currencies (name,factor) VALUES (:name, :factor);"); query.bindValue(":name", name); query.bindValue(":factor", factor); if (!query.exec()) { setError(query.lastError().text()); } else result=true; return result; } bool Azahar::deleteCurrency(const qulonglong &cid) { bool result = false; if (!db.isOpen()) db.open(); QSqlQuery query(db); query = QString("DELETE FROM currencies WHERE id=%1").arg(cid); if (!query.exec()) setError(query.lastError().text()); else result=true; return result; } // Reservations qulonglong Azahar::insertReservation(ReservationInfo info) { qulonglong result = 0; if (!db.isOpen()) db.open(); QSqlQuery query(db); query.prepare("INSERT INTO reservations (transaction_id, client_id, date, status, payment, total, totaltaxes, discount, item_discounts, profit) VALUES (:transaction, :client, :date, :status, :payment, :total, :totaltaxes, :discount, :item_discounts, :profit);"); query.bindValue(":transaction", info.transaction_id); query.bindValue(":client", info.client_id); query.bindValue(":payment", info.payment); query.bindValue(":date", info.date); query.bindValue(":status", info.status); query.bindValue(":total", info.total); query.bindValue(":totaltaxes", info.totalTaxes); query.bindValue(":discount", info.discount); query.bindValue(":item_discounts", info.item_discounts); query.bindValue(":profit", info.profit); if (!query.exec()) { setError(query.lastError().text()); qDebug()<< __FUNCTION__ << query.lastError().text(); } else result = query.lastInsertId().toULongLong(); return result; } bool Azahar::setReservationStatus(qulonglong id, reservationState state) { bool result = false; if (!db.isOpen()) db.open(); QSqlQuery query(db); query.prepare("UPDATE reservations SET status=:state WHERE id=:id;"); query.bindValue(":id", id); query.bindValue(":state", state); if (!query.exec()) setError(query.lastError().text()); else result=true; return result; } bool Azahar::setTransactionReservationStatus(const qulonglong &trId) { bool result = false; if (!db.isOpen()) db.open(); QSqlQuery query(db); query.prepare("UPDATE transactions SET state=:status WHERE id=:id;"); query.bindValue(":id", trId); query.bindValue(":status", tReserved); if (!query.exec()) setError(query.lastError().text()); else result=true; return result; } double Azahar::getReservationTotalAmount(qulonglong id) { double result=0; if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery myQuery(db); myQuery.prepare("SELECT total FROM reservations WHERE id=:id;"); myQuery.bindValue(":id", id); if (myQuery.exec() ) { while (myQuery.next()) { int fieldTotal = myQuery.record().indexOf("total"); result = myQuery.value(fieldTotal).toDouble(); } } else { setError(myQuery.lastError().text()); } } return result; } //FIXME: On dec 15 2011, i added payments for more than one payment double Azahar::getReservationPayment(qulonglong id) { double result=0; if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery myQuery(db); myQuery.prepare("SELECT payment FROM reservations WHERE id=:id;"); myQuery.bindValue(":id", id); if (myQuery.exec() ) { while (myQuery.next()) { int fieldTotal = myQuery.record().indexOf("payment"); result = myQuery.value(fieldTotal).toDouble(); } } else { setError(myQuery.lastError().text()); } } return result; } ReservationInfo Azahar::getReservationInfo(const qulonglong &id) { ReservationInfo result; result.id=0; if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery myQuery(db); myQuery.prepare("SELECT * FROM reservations WHERE id=:id;"); myQuery.bindValue(":id", id); if (myQuery.exec() ) { while (myQuery.next()) { int fieldPayment = myQuery.record().indexOf("payment"); int fieldClient = myQuery.record().indexOf("client_id"); int fieldTr = myQuery.record().indexOf("transaction_id"); int fieldDate = myQuery.record().indexOf("date"); int fieldStatus = myQuery.record().indexOf("status"); int fieldTotal = myQuery.record().indexOf("total"); int fieldTaxes = myQuery.record().indexOf("totaltaxes"); int fieldDisc = myQuery.record().indexOf("discount"); int fielditemD = myQuery.record().indexOf("item_discounts"); int fieldProfit = myQuery.record().indexOf("profit"); result.id = id; result.client_id = myQuery.value(fieldClient).toULongLong(); result.transaction_id = myQuery.value(fieldTr).toULongLong(); result.total = myQuery.value(fieldTotal).toDouble(); result.payment = myQuery.value(fieldPayment).toDouble(); result.date = myQuery.value(fieldDate).toDate(); result.status = myQuery.value(fieldStatus).toInt(); result.totalTaxes= myQuery.value(fieldTaxes).toDouble(); result.discount = myQuery.value(fieldDisc).toDouble(); result.item_discounts = myQuery.value(fielditemD).toString(); result.profit = myQuery.value(fieldProfit).toDouble(); } } else { setError(myQuery.lastError().text()); } } return result; } ReservationInfo Azahar::getReservationInfoFromTr(const qulonglong &trId) { ReservationInfo result; result.id=0; result.transaction_id = 0; if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery myQuery(db); myQuery.prepare("SELECT * FROM reservations WHERE transaction_id=:id;"); myQuery.bindValue(":id", trId); if (myQuery.exec() ) { while (myQuery.next()) { int fieldId = myQuery.record().indexOf("id"); int fieldPayment = myQuery.record().indexOf("payment"); int fieldClient = myQuery.record().indexOf("client_id"); int fieldTr = myQuery.record().indexOf("transaction_id"); int fieldDate = myQuery.record().indexOf("date"); int fieldStatus = myQuery.record().indexOf("status"); int fieldTotal = myQuery.record().indexOf("total"); int fieldTaxes = myQuery.record().indexOf("totaltaxes"); int fieldDisc = myQuery.record().indexOf("discount"); int fielditemD = myQuery.record().indexOf("item_discounts"); int fieldProfit = myQuery.record().indexOf("profit"); result.id = myQuery.value(fieldId).toULongLong(); result.client_id = myQuery.value(fieldClient).toULongLong(); result.transaction_id = myQuery.value(fieldTr).toULongLong(); result.total = myQuery.value(fieldTotal).toDouble(); result.payment = myQuery.value(fieldPayment).toDouble(); result.date = myQuery.value(fieldDate).toDate(); result.status = myQuery.value(fieldStatus).toInt(); result.totalTaxes= myQuery.value(fieldTaxes).toDouble(); result.discount = myQuery.value(fieldDisc).toDouble(); result.item_discounts = myQuery.value(fielditemD).toString(); result.profit = myQuery.value(fieldProfit).toDouble(); } } else { setError(myQuery.lastError().text()); } } return result; } bool Azahar::addReservationPayment(const qulonglong &rId, const double &amount ) { bool result = false; QDate today = QDate::currentDate(); if (!db.isOpen()) db.open(); QSqlQuery query(db); query.prepare("INSERT INTO reservation_payments (reservation_id, date, amount) VALUES (:reservation, :date, :amount);"); query.bindValue(":reservation", rId); query.bindValue(":date", today); query.bindValue(":amount", amount); if (!query.exec()) { setError(query.lastError().text()); qDebug()<< __FUNCTION__ << query.lastError().text(); } else result = true; return result; } QList<ReservationPayment> Azahar::getReservationPayments( const qulonglong &rId ) { QList<ReservationPayment> list; if (!db.isOpen()) db.open(); QSqlQuery myQuery(db); myQuery.prepare("SELECT * FROM reservation_payments WHERE reservation_id=:id;"); myQuery.bindValue(":id", rId); if (myQuery.exec() ) { while (myQuery.next()) { int fieldR = myQuery.record().indexOf("reservation_id"); int fieldId = myQuery.record().indexOf("id"); int fieldDate = myQuery.record().indexOf("date"); int fieldAmount = myQuery.record().indexOf("amount"); ReservationPayment result; result.id = myQuery.value(fieldId).toULongLong();; result.reservation_id = myQuery.value(fieldR).toULongLong(); result.amount = myQuery.value(fieldAmount).toDouble(); result.date = myQuery.value(fieldDate).toDate(); list.append(result); } } else { setError(myQuery.lastError().text()); } return list; } bool Azahar::setReservationPayment(const qulonglong &id, const double &amount) { bool result = false; if (!db.isOpen()) db.open(); QSqlQuery query(db); query.prepare("UPDATE reservations SET payment=:amount WHERE id=:id;"); query.bindValue(":id", id); query.bindValue(":amount", amount); if (!query.exec()) setError(query.lastError().text()); else result=true; return result; } CreditInfo Azahar::getCreditInfoForClient(const qulonglong &clientId, const bool &create) { CreditInfo result; result.id=0; result.clientId = 0; result.total = 0; if (!db.isOpen()) db.open(); if (db.isOpen()) { QSqlQuery myQuery(db); myQuery.prepare("SELECT * FROM credits WHERE customerid=:id;"); myQuery.bindValue(":id", clientId); if (myQuery.exec() ) { while (myQuery.next()) { int fieldId = myQuery.record().indexOf("id"); int fieldTotal = myQuery.record().indexOf("total"); result.clientId = clientId; result.id = myQuery.value(fieldId).toULongLong(); result.total = myQuery.value(fieldTotal).toDouble(); qDebug()<<__FUNCTION__<<" ----> Got credit:"<<result.id<<" for $"<<result.total; } qDebug()<<__FUNCTION__<<" Getting CREDIT INFO FOR CLIENT ID:"<<clientId<<" .. create="<<create<<" query size:"<<myQuery.size(); if (myQuery.size() <= 0 && create) { //NO RECORD FOUND, CREATE A NEW ONE. if ( getClientInfo(clientId).id > 0 ) { qDebug()<<__FUNCTION__<<" Creating new credit for client ID:"<<clientId; result.clientId = clientId; result.total = 0; qulonglong newId = insertCredit(result); result.id = newId; //now we can return result with the new credit. } else { //NOTE: INVALID CLIENT ID. INVALID CREDIT ALSO! result.clientId = 0; result.total = 0; qDebug()<<__FUNCTION__<<" CREDIT NOT FOUND AND NOT CREATED BECAUSE NO CLIENT FOUND WITH ID:"<<clientId; } } } else { setError(myQuery.lastError().text()); } } return result; } qulonglong Azahar::insertCredit(const CreditInfo &info) { qulonglong result = 0; if (!db.isOpen()) db.open(); QSqlQuery query(db); query.prepare("INSERT INTO credits (customerid, total) VALUES (:client, :total);"); query.bindValue(":client", info.clientId); query.bindValue(":total", info.total); if (!query.exec()) { setError(query.lastError().text()); qDebug()<< __FUNCTION__ << query.lastError().text(); } else result = query.lastInsertId().toULongLong(); return result; } bool Azahar::updateCredit(const CreditInfo &info) { bool result = false; if (!db.isOpen()) db.open(); QSqlQuery query(db); query.prepare("UPDATE credits SET customerid=:client, total=:total WHERE id=:id;"); query.bindValue(":client", info.clientId); query.bindValue(":total", info.total); query.bindValue(":id", info.id); if (!query.exec()) { setError(query.lastError().text()); qDebug()<< __FUNCTION__ << query.lastError().text(); } else result = query.lastInsertId().toULongLong(); return result; } QList<CreditHistoryInfo> Azahar:: getCreditHistoryForClient(const qulonglong &clientId, const int &lastDays) { QList<CreditHistoryInfo> result; if (!db.isOpen()) db.open(); if (db.isOpen()) { QDate today = QDate::currentDate(); QDate limitDate; if (lastDays > 0) limitDate = today.addDays(-lastDays); else limitDate = today.addDays(-30);//default is one month ago. QSqlQuery myQuery(db); myQuery.prepare("SELECT * FROM credit_history WHERE customerid=:clientId AND date >= :lDate ;"); myQuery.bindValue(":clientId", clientId); myQuery.bindValue(":lDate", limitDate); if (myQuery.exec()) { while (myQuery.next()) { int fieldId = myQuery.record().indexOf("id"); int fieldSaleId = myQuery.record().indexOf("saleid"); int fieldTotal = myQuery.record().indexOf("amount"); int fieldDate = myQuery.record().indexOf("date"); int fieldTime = myQuery.record().indexOf("time"); CreditHistoryInfo info; info.id = myQuery.value(fieldId).toULongLong(); info.customerId = clientId; info.saleId = myQuery.value(fieldSaleId).toULongLong(); info.amount = myQuery.value(fieldTotal).toDouble(); info.date = myQuery.value(fieldDate).toDate(); info.time = myQuery.value(fieldTime).toTime(); result.append(info); qDebug()<<__FUNCTION__<<" Got history for "<<info.customerId<<" SaleID:"<<info.saleId<<" Amount:"<<info.amount; } } else { qDebug()<<"ERROR: "<<myQuery.lastError(); } } return result; } qulonglong Azahar::insertCreditHistory(const CreditHistoryInfo &info) { qulonglong result = 0; if (!db.isOpen()) db.open(); QSqlQuery query(db); query.prepare("INSERT INTO credit_history (customerid, saleid, amount, date, time) VALUES (:clientId, :saleId, :amount, :date, :time);"); query.bindValue(":clientId", info.customerId); query.bindValue(":date", info.date); query.bindValue(":time", info.time); query.bindValue(":amount", info.amount); query.bindValue(":saleId", info.saleId); if (!query.exec()) { setError(query.lastError().text()); qDebug()<< __FUNCTION__ << query.lastError().text(); } else result = query.lastInsertId().toULongLong(); return result; } #include "azahar.moc"
189,815
C++
.cpp
4,736
34.451647
609
0.647088
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
752,792
mibitlineedit.cpp
hiramvillarreal_iotpos/mibitWidgets/mibitlineedit.cpp
/*************************************************************************** * Copyright (C) 2009 by Miguel Chavez Gamboa * * hiramvillarreal.ap@gmail.com * * * * This is based on the KLineEdit class * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "mibitlineedit.h" #include <QtGui> #include <QTimer> MibitLineEdit::MibitLineEdit( QWidget *parent ) : QLineEdit( parent ) { qDebug()<<"creating MibitLineEdit"; drawEmptyMsg = false; actualColor = 0; timer = new QTimer(this); shakeTimeToLive = 0; par = false; parTimes = 0; shakeTimer = new QTimer(this); shakeTimer->setInterval(20); timer->setInterval(30); //emptyMessage = emptyMessage(i18n("Type here...")); emptyMessage = "Type here..."; //what about localization? connect(this, SIGNAL(textEdited( const QString & ) ), SLOT(onTextChange(const QString &)) ); connect(timer, SIGNAL(timeout()), this, SLOT(stepColors())); connect(shakeTimer,SIGNAL(timeout()), this, SLOT(shakeIt())); } MibitLineEdit::~MibitLineEdit () { } QString MibitLineEdit::getEmptyMessage() const { return emptyMessage; } void MibitLineEdit::setEmptyMessage( const QString &msg ) { emptyMessage = msg; drawEmptyMsg = text().isEmpty(); update(); } void MibitLineEdit::paintEvent( QPaintEvent *ev ) { QLineEdit::paintEvent( ev ); if ( text().isEmpty() ) { QPainter p(this); QFont f = font(); f.setItalic(true); p.setFont(f); QColor color(palette().color(foregroundRole())); color.setAlphaF(0.5); p.setPen(color); //FIXME: fugly alert! // qlineedit uses an internal qstyleoption set to figure this out // and then adds a hardcoded 2 pixel interior to that. // probably requires fixes to Qt itself to do this cleanly // see define horizontalMargin 2 in qlineedit.cpp QStyleOptionFrame opt; initStyleOption(&opt); QRect cr = style()->subElementRect(QStyle::SE_LineEditContents, &opt, this); cr.setLeft(cr.left() + 2); cr.setRight(cr.right() - 2); p.drawText(cr, Qt::AlignLeft|Qt::AlignVCenter, emptyMessage); } } void MibitLineEdit::setError( const QString& msg ) { timer->start(); //timer for colors //set tooltip setToolTip(msg); if (autoClear) { //create a timer to clear the error. QTimer::singleShot(5000,this,SLOT(clearError())); } } void MibitLineEdit::stepColors() { if (actualColor > 199) { actualColor=0; timer->stop(); return; } else { actualColor=actualColor+2; } setStyleSheet(QString(" QLineEdit { background: rgb(255,%1,0); color:white; font-weight: bold;}").arg(actualColor)); } void MibitLineEdit::clearError( ) { timer->stop(); //disable timer to disable stepColors. setStyleSheet(""); setToolTip(""); } ///This function needs to be called before the setError() one... to enable the Qtimer::singleShot void MibitLineEdit::setAutoClearError( const bool& state ) { autoClear = state; } void MibitLineEdit::onTextChange(const QString &) { //clear the error clearError(); } void MibitLineEdit::focusInEvent( QFocusEvent *ev ) { if ( drawEmptyMsg ) { drawEmptyMsg = false; update(); } QLineEdit::focusInEvent( ev ); } void MibitLineEdit::focusOutEvent( QFocusEvent *ev ) { if ( text().isEmpty() ) { drawEmptyMsg = true; update(); } QLineEdit::focusOutEvent( ev ); } void MibitLineEdit::keyPressEvent ( QKeyEvent * event ) { // Check for our special keys +,Enter (specific for iotposPOS) // The Enter key is the one located at the numeric pad. The other is called RETURN. if ( event->key() == Qt::Key_Plus || event->key() == Qt::Key_Enter ) emit plusKeyPressed(); //anyway we must send enter and + key events... QLineEdit::keyPressEvent(event); } void MibitLineEdit::shake() { shakeTimer->start(); QTimer::singleShot(3000,shakeTimer,SLOT(stop())); } void MibitLineEdit::shakeIt() { if (par) { if (parTimes < 5) { if ( parTimes % 2 == 0 ) setGeometry(geometry().x()-3, geometry().y()+3, geometry().width(), geometry().height()); else setGeometry(geometry().x()+3, geometry().y()+3, geometry().width(), geometry().height()); } parTimes++; if (parTimes >39) { parTimes = 0; } } else { if (parTimes < 5) { if ( parTimes % 2 == 0 ) setGeometry(geometry().x()+3, geometry().y()-3, geometry().width(), geometry().height()); else setGeometry(geometry().x()-3, geometry().y()-3, geometry().width(), geometry().height()); } } par = !par; }
6,259
C++
.cpp
172
31.093023
120
0.5645
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
752,793
mibitnotifier.cpp
hiramvillarreal_iotpos/mibitWidgets/mibitnotifier.cpp
/*************************************************************************** * Copyright (C) 2009 by Miguel Chavez Gamboa * * hiramvillarreal.ap@gmail.com * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "mibitnotifier.h" #include <QPixmap> #include <QIcon> #include <QString> #include <QLabel> #include <QHBoxLayout> #include <QVBoxLayout> #include <QTimeLine> #include <QTimer> #include <QDebug> MibitNotifier::MibitNotifier(QWidget *parent, const QString &file, const QPixmap &icon, const bool &onTop) : QSvgWidget( parent ) { if (file != 0) setSVG(file); m_parent = parent; m_onTop = onTop; m_canClose = false; m_fileName = file; setMinimumHeight(100); setFixedSize(0,0); //until show we grow it setMaxHeight(max_H); //default sizes setMaxWidth(max_W); animRate = 500; //default animation speed (half second rate). img = new QLabel(); hLayout = new QHBoxLayout(); message = new QLabel(""); img->setPixmap(icon); img->setMaximumHeight(54); //the icon size is hardcoded now. img->setMaximumWidth(54); img->setAlignment(Qt::AlignLeft); img->setMargin(4); setLayout(hLayout); message->setWordWrap(true); message->setAlignment(Qt::AlignJustify|Qt::AlignVCenter); message->setMargin(10); QSizePolicy sizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); sizePolicy.setHeightForWidth(message->sizePolicy().hasHeightForWidth()); message->setSizePolicy(sizePolicy); hLayout->addWidget(img,0,Qt::AlignLeft); hLayout->addWidget(message,1,Qt::AlignJustify); timeLine = new QTimeLine(animRate, this); connect(timeLine, SIGNAL(frameChanged(int)), this, SLOT(animate(int))); connect(timeLine,SIGNAL(finished()), this, SLOT(onAnimationFinished())); } void MibitNotifier::showNotification( const QString &msg, const int &timeToLive) //timeToLive = 0 : not auto hide it. { /// Warning: if a tip is showing, if another showTip() is called, it is ignored. if (timeLine->state() == QTimeLine::NotRunning && !m_canClose /*size().height() <= 0*/) { //set default msg if the sent is empty. if (!msg.isEmpty()) { setMessage( msg ); message->setMinimumWidth(maxWidth-70); } else setMessage(message->text()); //change svg skin if is not on top. if (!m_onTop) setSVG("rotated_"+m_fileName); else setSVG(m_fileName); setGeometry(-1000,-1000,0,0); show(); //update steps for animation, now that the window is showing. int maxStep; int minStep = 0; if ( m_onTop ) { minStep = -maxHeight; maxStep = 0; } else { maxStep = m_parent->geometry().height()-maxHeight; minStep = m_parent->geometry().height(); } //qDebug()<<" MaxStep:"<<maxStep<<" MinStep:"<<minStep; timeLine->setFrameRange(minStep,maxStep); //make it grow timeLine->setDirection(QTimeLine::Forward); timeLine->start(); if (timeToLive > 0 ) QTimer::singleShot(timeToLive,this,SLOT(hideDialog())); } } void MibitNotifier::animate(const int &step) { //get some sizes... QRect windowGeom = m_parent->geometry(); int midPointX = (windowGeom.width()/2); int newX; int newW; QRect dRect; if (maxWidth < min_W ) newW = min_W; else newW = maxWidth; if ((midPointX-(newW/2)) < 0) newX = 0; else newX = midPointX - (newW/2); dRect.setX(newX); setFixedWidth(newW); dRect.setY(step); setGeometry(dRect); setFixedHeight(maxHeight); if (m_onTop) { // Sliding from top if (step == -maxHeight) setFixedHeight(0); } else { // Sliding from bottom if (step == m_parent->geometry().height()) setFixedHeight(0); } } void MibitNotifier::hideOnUserRequest() { hideDialog(); } void MibitNotifier::hideDialog() { if ( m_canClose ) { timeLine->toggleDirection();//reverse! timeLine->start(); } } void MibitNotifier::onAnimationFinished() { if (timeLine->direction() == QTimeLine::Backward) { close(); m_canClose = false; } else m_canClose = true; } void MibitNotifier::setOnBottom(const bool &sOnBottom) { // only changes the position when the notification is not showing.. if (timeLine->state() == QTimeLine::NotRunning && size().height() <= 0) m_onTop = !sOnBottom; } void MibitNotifier::setSVG(const QString &file) { load(file); } void MibitNotifier::setIcon(const QPixmap &icon) { img->setPixmap(icon); } void MibitNotifier::setMessage(const QString &msg) { message->setText(msg); } void MibitNotifier::setTextColor(const QString &color) { message->setStyleSheet(QString("color:%1").arg(color)); } void MibitNotifier::mousePressEvent ( QMouseEvent * ) { hideOnUserRequest(); } MibitNotifier::~MibitNotifier() {}
6,165
C++
.cpp
157
34.66879
117
0.604651
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
752,794
mibitfloatpanel.cpp
hiramvillarreal_iotpos/mibitWidgets/mibitfloatpanel.cpp
/*************************************************************************** * Copyright (C) 2009 by Miguel Chavez Gamboa * * hiramvillarreal.ap@gmail.com * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "mibitfloatpanel.h" #include <QPixmap> #include <QString> #include <QHBoxLayout> #include <QTimeLine> #include <QTimer> #include <QMouseEvent> #include <QEvent> #include <QDebug> MibitFloatPanel::MibitFloatPanel(QWidget *parent, const QString &file, PanelPosition position, const int &w, const int &h) : QSvgWidget( parent ) { //setMouseTracking(true); m_hideTotally = false; margin = 7; if (file != 0) setSVG(file); m_position = position; m_mode = pmAuto; m_parent = parent; m_fileName = file; canBeHidden = false; //at the begining is hidden. setMinimumHeight(h); setMinimumWidth(w); setMaxHeight(h); setMaxWidth(w); setFixedHeight(0); animRate = 500; //default animation speed (half a second rate). hLayout = new QHBoxLayout(); setLayout(hLayout); //Postition it on its place QTimer::singleShot(100,this,SLOT(reposition())); timeLine = new QTimeLine(animRate, this); connect(timeLine, SIGNAL(frameChanged(int)), this, SLOT(animate(int))); connect(timeLine,SIGNAL(finished()), this, SLOT(onAnimationFinished())); } void MibitFloatPanel::reposition() { QRect windowGeom = m_parent->geometry(); int midPointX = (windowGeom.width()/2); int midPointY = (windowGeom.height()/2); int newX; int newY; QRect dRect; if ((midPointX-(maxWidth/2)) < 0) newX = 0; else newX = midPointX - (maxWidth/2); if ((midPointY-(maxHeight/2)) < 0) newY = 0; else newY = midPointY - (maxHeight/2); //qDebug()<<"parent geometry:"<<windowGeom; switch (m_position) { case Top: newY = margin-maxHeight; break; case Bottom: newY = m_parent->height()+height()-margin; break; case Left: newX = margin-maxWidth; break; case Right: newX = m_parent->width()-margin; break; } dRect.setX(newX); dRect.setY(newY); setFixedWidth(maxWidth); //width maybe is not yet defined. setFixedHeight(maxHeight); setGeometry(dRect); } void MibitFloatPanel::addWidget(QWidget * widget) { hLayout->addWidget(widget, 1, Qt::AlignCenter); } void MibitFloatPanel::showPanel() { if (timeLine->state() == QTimeLine::NotRunning && !canBeHidden) { setGeometry(-1000,-1000,0,0); show(); //update steps for animation, now that the panel is showing. int maxStep = 0, minStep = 0; switch (m_position) { case Top : minStep = -maxHeight+margin; maxStep = -6; break; case Bottom: maxStep = m_parent->geometry().height()-maxHeight; minStep = m_parent->geometry().height()-margin; break; case Left: minStep = -maxWidth+margin; maxStep = -6; break; case Right: minStep = m_parent->geometry().width()-margin; maxStep = m_parent->geometry().width()-maxWidth; break; default: break; } timeLine->setFrameRange(minStep,maxStep); //make it grow timeLine->setDirection(QTimeLine::Forward); timeLine->start(); } } void MibitFloatPanel::animate(const int &step) { //get some sizes... QRect windowGeom = m_parent->geometry(); int midPointX = (windowGeom.width()/2); int midPointY = (windowGeom.height()/2); int newX; int newY; QRect dRect; if ((midPointX-(maxWidth/2)) < 0) newX = 0; else newX = midPointX - (maxWidth/2); if ((midPointY-(maxHeight/2)) < 0) newY = 0; else newY = midPointY - (maxHeight/2); switch (m_position) { case Bottom: case Top: dRect.setX(newX); dRect.setY(step); break; case Left: case Right: dRect.setY(newY); dRect.setX(step); break; default: break; } dRect.setWidth(maxWidth); dRect.setHeight(maxHeight); setGeometry(dRect); setFixedHeight(maxHeight); setFixedWidth(maxWidth); } void MibitFloatPanel::hideOnUserRequest() { hideDialog(); emit hiddenOnUserRequest(); } void MibitFloatPanel::hideDialog() { if ( canBeHidden ) { timeLine->setDirection(QTimeLine::Backward); //reverse! timeLine->start(); } } void MibitFloatPanel::onAnimationFinished() { if (timeLine->direction() == QTimeLine::Forward) { canBeHidden = true; } else { //Backward canBeHidden = false; if (m_hideTotally) hide(); } } void MibitFloatPanel::setPosition(const PanelPosition pos) { // only changes the position when the notification is not showing.. if (timeLine->state() == QTimeLine::NotRunning && !canBeHidden) { m_position = pos; //recalculate its rect and show it there... reposition(); } } //NOTE: The svg file is not rendered correctly. It does not render the blur, i.e. the shadows void MibitFloatPanel::setSVG(const QString &file) { load(file); } void MibitFloatPanel::enterEvent ( QEvent * ) { if (m_mode == pmAuto) QTimer::singleShot(300,this,SLOT(showPanelDelayed())); } //This is to delay the panel showing, for those inconvenient times where you dont want to //get the floatingpanel to appear because you are only passing above the 10pixes of the panel //to arrive to another widget. void MibitFloatPanel::showPanelDelayed() { if (underMouse()) { QTimer::singleShot(100,this,SLOT(showPanel())); } } void MibitFloatPanel::leaveEvent( QEvent * ) { if (m_mode == pmAuto) QTimer::singleShot(100,this,SLOT(hideOnUserRequest())); } void MibitFloatPanel::keyPressEvent ( QKeyEvent * event ) { if ( event->key() == Qt::Key_Escape ) { if (m_mode == pmManual) hideOnUserRequest(); } //else ignore event. } void MibitFloatPanel::reParent(QWidget *newparent) { setParent(newparent); m_parent = newparent; //update reposition(); } //HACK: //This is to fix position, the bad position is because when positioned if //the parent is not showing, the parent size is small (100,30). //Calling this method when the parent is showing ensures the position is correct. void MibitFloatPanel::fixPos() { hide(); reposition(); QTimer::singleShot(100, this, SLOT(show())); } MibitFloatPanel::~MibitFloatPanel() {}
7,903
C++
.cpp
229
29.078603
122
0.599372
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
752,795
mibittip.cpp
hiramvillarreal_iotpos/mibitWidgets/mibittip.cpp
/*************************************************************************** * Copyright (C) 2009 by Miguel Chavez Gamboa * * hiramvillarreal.ap@gmail.com * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "mibittip.h" #include <QtGui> #include <QTimeLine> #include <QSize> #include <QRect> #include <QLabel> #include <QPixmap> //#include <QGraphicsSvgItem MibitTip::MibitTip( QWidget *parent, QWidget *partner, const QString &file, const QPixmap &icon, const TipPosition &drawOn ) : QSvgWidget( parent ) { if (file != 0 ) { setSVG(file); fileName = file; } else fileName = ""; //set temporal max h & w --- and predefined ones. maxWidth = 200; maxHeight= 200; setMaximumHeight(maxHeight); setMinimumHeight(0); setFixedHeight(0); //save parent and partner pointers m_parent = parent; m_partner= partner; m_tipPosition = drawOn; closedByUser = false; timeToLive = 4000; //create labels img = new QLabel(); layout = new QVBoxLayout(); text = new QLabel(""); setIcon(icon); img->setMaximumHeight(32); img->setAlignment(Qt::AlignCenter); if ( m_tipPosition == tpAbove ) { layout->addWidget(text); layout->addWidget(img); // a hack... "rotated_"+ load(fileName); } else { layout->addWidget(img); layout->addWidget(text); } layout->setContentsMargins(8, 8, 8, 8); //setMargin(9); setLayout(layout); text->setWordWrap(true); text->setMargin(5); timeLine = new QTimeLine(1000, this); timeLine->setFrameRange(0, maxHeight); connect(timeLine, SIGNAL(frameChanged(int)), this, SLOT(morph(int))); } MibitTip::~MibitTip () { } void MibitTip::showTip( const QString &msg, const int ttl) { timeToLive = ttl; timeLine->setFrameRange(0, maxHeight); text->setText( msg ); /// Warning: if a tip is showing, if another showTip() is called, it not animated, just changed the msg. if (timeLine->state() == QTimeLine::NotRunning && size().height() <= 0) { show(); //make it grow timeLine->setDirection(QTimeLine::Forward); timeLine->start(); //autoShrink QTimer::singleShot(timeToLive-1000, this, SLOT(autoHide())); } //else qDebug()<<"Animation running... sorry"; } void MibitTip::morph(int newSize) { //get some positions... QRect listRect(m_partner->rect()); QPoint below = m_partner->mapToGlobal(listRect.bottomLeft()); QPoint above = m_partner->mapToGlobal(listRect.topLeft()); QPoint windowPos = m_parent->mapToGlobal(QPoint(0,0)); //the window is the parent, we assume this. //correct global positions with current window position. below = below - windowPos; above = above -windowPos; //where to draw above or below its partner if ( m_tipPosition == tpBelow ) { //here will grow from top to bottom listRect.setX(below.x()+10); listRect.setY(below.y()-3); setGeometry(listRect); //set fixed width and height } else { // here will grow from bottom to top and the image inverted //load the inverted background image //QGraphicsSvgItem svgItem(fileName); //svgItem.rotate(180); //QSvgRenderer *theRenderer = renderer(); /// How to pass the rotated svg item to the renderer or QSvgWidget loader? int newY = above.y() - newSize + 3; listRect.setX(above.x()+10); listRect.setY(newY); setGeometry(listRect); } setFixedHeight(newSize); setFixedWidth(m_partner->width()-20); //qDebug()<<"New size:"<<newSize; } void MibitTip::autoHide() { if ( !closedByUser) { timeLine->setDirection(QTimeLine::Backward); // timeLine->toggleDirection(); //reverse! timeLine->start(); } else closedByUser = !closedByUser; } void MibitTip::setSVG(const QString &file) { load(file); //we can load also from a Byte Array. } void MibitTip::setIcon(const QPixmap &icon) { img->setPixmap(icon); } void MibitTip::mousePressEvent ( QMouseEvent * ) { autoHide(); //we simply want to close the tip on any mouse click closedByUser = true; }
5,474
C++
.cpp
139
34.719424
125
0.59108
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
752,796
mibitpassworddlg.cpp
hiramvillarreal_iotpos/mibitWidgets/mibitpassworddlg.cpp
/*************************************************************************** * Copyright (C) 2009-2011 by Miguel Chavez Gamboa * * hiramvillarreal.ap@gmail.com * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "mibitpassworddlg.h" #include <QPixmap> #include <QString> #include <QLabel> #include <QHBoxLayout> #include <QVBoxLayout> #include <QTimeLine> //#include "ease-effects/qtimeline.h" #include <QTimer> #include <QPushButton> #include <QKeyEvent> #include <QDebug> MibitPasswordDialog::MibitPasswordDialog( QWidget *parent, const QString &msg, const QString &file, const QPixmap &icon, AnimationTypeP animation ) : QSvgWidget( parent ) //setting parent = 0 makes the dialog a window, capable to use the setWidowModality(Qt::ApplicationModal). { //setWindowFlags(Qt::FramelessWindowHint);//this makes frameless but with a background.. and cannot be transparent! //setWindowModality(Qt::ApplicationModal); //This only works for windows (not widgets like this) if (file != 0) setSVG(file); m_parent = parent; animType = animation; setMinimumHeight(100); setFixedSize(0,0); //until show we grow it setMaxHeight(pmaxH); //default sizes setMaxWidth(pmaxW); animRate = 500; //default animation speed (half second rate). shakeTimeToLive = 0; par = false; parTimes = 0; if (closeMsg.isEmpty()) closeMsg = "Ok"; img = new QLabel(); hLayout = new QHBoxLayout(); vLayout = new QVBoxLayout(); text = new QLabel(msg); //btnClose = new QPushButton(closeMsg); ///TODO: what about translations??? editPassword = new QLineEdit(this); shakeTimer = new QTimer(this); shakeTimer->setInterval(20); img->setPixmap(icon); img->setMaximumHeight(70); //the icon size is hardcoded now. img->setMaximumWidth(70); img->setAlignment(Qt::AlignLeft); img->setMargin(4); //btnClose->setMaximumWidth(120); editPassword->setEchoMode(QLineEdit::Password); setLayout(vLayout); text->setWordWrap(true); text->setAlignment(Qt::AlignJustify|Qt::AlignVCenter); text->setMargin(5); hLayout->addWidget(img,0,Qt::AlignCenter); hLayout->addWidget(text,1,Qt::AlignCenter); vLayout->addLayout(hLayout,2); vLayout->addWidget(editPassword,1,Qt::AlignCenter); //vLayout->addWidget(btnClose,1,Qt::AlignCenter); timeLine = new QTimeLine(animRate, this); wTimeLine = new QTimeLine(2000, this); wTimeLine->setFrameRange(90,190); wTimeLine->setCurveShape(QTimeLine::CosineCurve); connect(timeLine, SIGNAL(frameChanged(int)), this, SLOT(animate(int))); connect(wTimeLine, SIGNAL(frameChanged(int)), this, SLOT(waveIt(int))); //connect(btnClose,SIGNAL(clicked()),this, SLOT(hideDialog())); connect(timeLine,SIGNAL(finished()), this, SLOT(onAnimationFinished())); connect(shakeTimer,SIGNAL(timeout()), this, SLOT(shakeIt())); } MibitPasswordDialog::~MibitPasswordDialog() { } void MibitPasswordDialog::showDialog(const QString &msg, AnimationTypeP animation ) { //set default msg if the sent is empty. Also set the animation -the same way-. if (msg.isEmpty()) setMessage(text->text()); else setMessage( msg ); if (animation == 0) setAnimationType( atpSlideDown ); else setAnimationType( animation ); setGeometry(-1000,-1000,0,0); show(); //update steps for animation, now that the window is showing. int maxStep = 0, minStep = 0; switch (animType) { case atpSlideDown: maxStep = (m_parent->geometry().height()/2)-(maxHeight/2); minStep = -maxHeight; break; case atpSlideUp: maxStep = (m_parent->geometry().height()/2)-(maxHeight/2); minStep = maxHeight + m_parent->geometry().height(); break; case atpGrowCenterH: maxStep = maxWidth; minStep = 0; break; case atpGrowCenterV: maxStep= maxHeight; minStep = 0; break; } #if QT_VERSION >= 0x040600 timeLine->setEasingCurve(QEasingCurve::OutBounce); // QEasingCurve::OutBounce is since Qt 4.6 only.. will not compile with Qt 4.5 or earlier #endif timeLine->setFrameRange(minStep,maxStep); //make it grow... timeLine->setDirection(QTimeLine::Forward); timeLine->start(); editPassword->setFocus(); } void MibitPasswordDialog::animate(const int &step) { //get some sizes... QRect windowGeom = m_parent->geometry(); int midPointX = (windowGeom.width()/2); int midPointY = (windowGeom.height()/2); int newY; int newX; QRect dRect; switch (animType) { case atpGrowCenterV: // Grow from Center Vertically.. if ((midPointY - step/2) < 0 ) newY = 0; else newY = midPointY - step/2; if ((midPointX-(maxWidth/2)) < 0) newX = 0; else newX = midPointX - maxWidth/2; dRect.setX(newX); dRect.setY(newY); dRect.setWidth(step); dRect.setHeight(maxHeight); setGeometry(dRect); setFixedHeight(step); setFixedWidth(maxWidth); break; case atpGrowCenterH: // Grow from Center Horizontally... if ((midPointX - step/2) < 0 ) newX = 0; else newX = midPointX - step/2; if ((midPointY-(maxHeight/2)) < 0) newY = 0; else newY = midPointY - maxHeight/2; dRect.setX(newX); dRect.setY(newY); dRect.setWidth(maxWidth); dRect.setHeight(step); setGeometry(dRect); setFixedHeight(maxHeight); setFixedWidth(step); break; case atpSlideDown: // slide Up case atpSlideUp: // Slide down if ((midPointX-(maxWidth/2)) < 0) newX = 0; else newX = midPointX - maxWidth/2; dRect.setX(newX); dRect.setY(step); dRect.setWidth(maxWidth); dRect.setHeight(maxHeight); setGeometry(dRect); setFixedHeight(maxHeight); setFixedWidth(maxWidth); break; default: break; } } void MibitPasswordDialog::hideDialog() { timeLine->toggleDirection();//reverse! timeLine->start(); } void MibitPasswordDialog::onAnimationFinished() { if (timeLine->direction() == QTimeLine::Backward) { close(); shakeTimer->stop(); } } void MibitPasswordDialog::setSVG(const QString &file) { load(file); } void MibitPasswordDialog::setIcon(const QPixmap &icon) { img->setPixmap(icon); } void MibitPasswordDialog::setMessage(const QString &msg) { text->setText(msg); } void MibitPasswordDialog::setTextColor(const QString &color) { text->setStyleSheet(QString("color:%1").arg(color)); } void MibitPasswordDialog::shake() { shakeTimer->start(); if ( shakeTimeToLive > 0 ) QTimer::singleShot(shakeTimeToLive,shakeTimer,SLOT(stop())); } void MibitPasswordDialog::shakeIt() { if (par) { if (parTimes < 5) { if ( parTimes % 2 == 0 ) setGeometry(geometry().x()-3, geometry().y()+3, geometry().width(), geometry().height()); else setGeometry(geometry().x()+3, geometry().y()+3, geometry().width(), geometry().height()); } parTimes++; if (parTimes >39) { parTimes = 0; } } else { if (parTimes < 5) { if ( parTimes % 2 == 0 ) setGeometry(geometry().x()+3, geometry().y()-3, geometry().width(), geometry().height()); else setGeometry(geometry().x()-3, geometry().y()-3, geometry().width(), geometry().height()); } } par = !par; } void MibitPasswordDialog::wave() { wTimeLine->start(); } void MibitPasswordDialog::waveIt(const int &step) { if (timeLine->state() == QTimeLine::NotRunning || !shakeTimer->isActive() ) { setGeometry(geometry().x(),step, geometry().width(), geometry().height()); } else qDebug()<<"Dialog is in active animation."; } void MibitPasswordDialog::keyPressEvent ( QKeyEvent * event ) { if ( event->key() == Qt::Key_Escape ) { // hideDialog(); // on password dialog ESC key pressed, we cannot close it. qDebug()<<"MibitPasswordDialog::ESC key pressed"; } else if ( event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return ) { //emit the enter event. qDebug()<<"MibitPasswordDialog::Enter key pressed"; emit returnPressed(); } }
9,790
C++
.cpp
248
33.362903
147
0.606816
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
752,797
mibitdialog.cpp
hiramvillarreal_iotpos/mibitWidgets/mibitdialog.cpp
/*************************************************************************** * Copyright (C) 2009 by Miguel Chavez Gamboa * * miguel@lemonpos.org * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "mibitdialog.h" #include <QPixmap> #include <QString> #include <QLabel> #include <QHBoxLayout> #include <QVBoxLayout> #include <QTimeLine> #include "ease-effects/qtimeline.h" #include <QTimer> #include <QPushButton> #include <QKeyEvent> #include <QDebug> MibitDialog::MibitDialog( QWidget *parent, const QString &msg, const QString &file, const QPixmap &icon, AnimationType animation ) : QSvgWidget( parent ) { if (file != 0) setSVG(file); m_parent = parent; animType = animation; setMinimumHeight(100); setFixedSize(0,0); //until show we grow it setMaxHeight(maxH); //default sizes setMaxWidth(maxW); animRate = 500; //default animation speed (half second rate). shakeTimeToLive = 0; par = false; parTimes = 0; img = new QLabel(); hLayout = new QHBoxLayout(); vLayout = new QVBoxLayout(); text = new QLabel(msg); btnClose = new QPushButton("Close"); ///TODO: what about translations??? shakeTimer = new QTimer(this); shakeTimer->setInterval(20); img->setPixmap(icon); img->setMaximumHeight(54); //the icon size is hardcoded now. img->setMaximumWidth(54); img->setAlignment(Qt::AlignLeft); img->setMargin(4); btnClose->setMaximumWidth(120); setLayout(vLayout); text->setWordWrap(true); text->setAlignment(Qt::AlignJustify|Qt::AlignVCenter); text->setMargin(5); hLayout->addWidget(img,0,Qt::AlignCenter); hLayout->addWidget(text,1,Qt::AlignCenter); vLayout->addLayout(hLayout,2); vLayout->addWidget(btnClose,1,Qt::AlignCenter); timeLine = new QTimeLine(animRate, this); wTimeLine = new QTimeLine(2000, this); wTimeLine->setFrameRange(90,190); wTimeLine->setCurveShape(QTimeLine::CosineCurve); connect(timeLine, SIGNAL(frameChanged(int)), this, SLOT(animate(int))); connect(wTimeLine, SIGNAL(frameChanged(int)), this, SLOT(waveIt(int))); connect(btnClose,SIGNAL(clicked()),this, SLOT(hideDialog())); connect(timeLine,SIGNAL(finished()), this, SLOT(onAnimationFinished())); connect(shakeTimer,SIGNAL(timeout()), this, SLOT(shakeIt())); } MibitDialog::~MibitDialog() { } void MibitDialog::showDialog(const QString &msg, AnimationType animation ) { //set default msg if the sent is empty. Also set the animation -the same way-. if (msg.isEmpty()) setMessage(text->text()); else setMessage( msg ); if (animation == 0) setAnimationType( atSlideDown ); else setAnimationType( animation ); setGeometry(-1000,-1000,0,0); show(); //update steps for animation, now that the window is showing. int maxStep; int minStep = 0; switch (animType) { case atSlideDown: maxStep = (m_parent->geometry().height()/2)-(maxHeight/2); minStep = -maxHeight; break; case atSlideUp: maxStep = (m_parent->geometry().height()/2)-(maxHeight/2); minStep = maxHeight + m_parent->geometry().height(); break; case atGrowCenterH: maxStep = maxWidth; minStep = 0; break; case atGrowCenterV: maxStep= maxHeight; minStep = 0; break; } /// QTimeLine: Hacer una curva de movimiento armonico criticamente amortiguado. timeLine->setFrameRange(minStep,maxStep); //make it grow... timeLine->setDirection(QTimeLine::Forward); timeLine->start(); btnClose->setFocus(); } void MibitDialog::animate(const int &step) { //get some sizes... QRect windowGeom = m_parent->geometry(); int midPointX = (windowGeom.width()/2); int midPointY = (windowGeom.height()/2); int newY; int newX; QRect dRect; switch (animType) { case atGrowCenterV: // Grow from Center Vertically.. if ((midPointY - step/2) < 0 ) newY = 0; else newY = midPointY - step/2; if ((midPointX-(maxWidth/2)) < 0) newX = 0; else newX = midPointX - maxWidth/2; dRect.setX(newX); dRect.setY(newY); dRect.setWidth(step); dRect.setHeight(maxHeight); setGeometry(dRect); setFixedHeight(step); setFixedWidth(maxWidth); break; case atGrowCenterH: // Grow from Center Horizontally... if ((midPointX - step/2) < 0 ) newX = 0; else newX = midPointX - step/2; if ((midPointY-(maxHeight/2)) < 0) newY = 0; else newY = midPointY - maxHeight/2; dRect.setX(newX); dRect.setY(newY); dRect.setWidth(maxWidth); dRect.setHeight(step); setGeometry(dRect); setFixedHeight(maxHeight); setFixedWidth(step); break; case atSlideDown: // slide Up case atSlideUp: // Slide down if ((midPointX-(maxWidth/2)) < 0) newX = 0; else newX = midPointX - maxWidth/2; dRect.setX(newX); dRect.setY(step); dRect.setWidth(maxWidth); dRect.setHeight(maxHeight); setGeometry(dRect); setFixedHeight(maxHeight); setFixedWidth(maxWidth); break; default: break; } } void MibitDialog::hideDialog() { timeLine->toggleDirection();//reverse! timeLine->start(); } void MibitDialog::onAnimationFinished() { if (timeLine->direction() == QTimeLine::Backward) { close(); shakeTimer->stop(); } } void MibitDialog::setSVG(const QString &file) { load(file); } void MibitDialog::setIcon(const QPixmap &icon) { img->setPixmap(icon); } void MibitDialog::setMessage(const QString &msg) { text->setText(msg); } void MibitDialog::setTextColor(const QString &color) { text->setStyleSheet(QString("color:%1").arg(color)); } void MibitDialog::shake() { shakeTimer->start(); if ( shakeTimeToLive > 0 ) QTimer::singleShot(shakeTimeToLive,shakeTimer,SLOT(stop())); } void MibitDialog::shakeIt() { if (par) { if (parTimes < 5) { if ( parTimes % 2 == 0 ) setGeometry(geometry().x()-3, geometry().y()+3, geometry().width(), geometry().height()); else setGeometry(geometry().x()+3, geometry().y()+3, geometry().width(), geometry().height()); } parTimes++; if (parTimes >39) { parTimes = 0; } } else { if (parTimes < 5) { if ( parTimes % 2 == 0 ) setGeometry(geometry().x()+3, geometry().y()-3, geometry().width(), geometry().height()); else setGeometry(geometry().x()-3, geometry().y()-3, geometry().width(), geometry().height()); } } par = !par; } void MibitDialog::wave() { wTimeLine->start(); } void MibitDialog::waveIt(const int &step) { if (timeLine->state() == QTimeLine::NotRunning || !shakeTimer->isActive() ) { setGeometry(geometry().x(),step, geometry().width(), geometry().height()); } else qDebug()<<"Dialog is in active animation."; } void MibitDialog::keyPressEvent ( QKeyEvent * event ) { if ( event->key() == Qt::Key_Escape ) { hideDialog(); } //else ignore event. }
8,677
C++
.cpp
233
31.154506
130
0.58918
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
752,798
bundlelist.cpp
hiramvillarreal_iotpos/src/bundlelist.cpp
/*************************************************************************** * Copyright © 2012 by Miguel Chavez Gamboa * * hiramvillarreal.ap@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include <QMultiHash> #include <QDebug> #include <QtSql> #include "bundlelist.h" #include "../dataAccess/azahar.h" BundleList::BundleList() { bundles.clear(); } bool BundleList::contains(const qulonglong &itemCode) { return bundles.contains(itemCode); //it is just a wrapper function } void BundleList::addItem(const BundleInfo &bundle, const int &maxItems) { //We start our search for a free slot and bundle. if ( bundles.isEmpty() ) { //As there are no bundles, then we add a new one. qDebug()<<"Empty bundles... inserting new one"; insertNewBundle(bundle, maxItems); } else { //BEGIN: No empty bundles list. Search starts here. int inserted = 0; qDebug()<<"Going to search "<<bundle.product_id<<"x"<<bundle.qty<<" @"<<bundle.price; QMultiHash<qulonglong, BundleInfo>::iterator i = bundles.find(bundle.product_id); //if no bundle for the product, then the next while loop will not be executed while (i != bundles.end() && i.key() == bundle.product_id) { qDebug()<<"Examining Bundle | Qty:"<<i.value().qty<<" Price:"<<i.value().price<<" Product:"<<i.value().product_id<<" | "<<" Required Qty:"<< bundle.qty<<" Required Product:"<<bundle.product_id; BundleInfo current = i.value(); // for working with current instead of i.value()... qDebug()<<current.qty<<" @ "<<current.price; if ( current.qty < maxItems ) { // Has some free slots... how many free? int freeSlots = maxItems - current.qty; qDebug()<<"Free Slots:"<<freeSlots<<" Filled Slots:"<<current.qty; if ( freeSlots > 0 ){ //so, there are free slots, but how many do we need? double needed = bundle.qty; qDebug()<<"Needed Slots:"<<needed; //We occupy the free slots NEEDED ( and allowed for the bundle ) if ( needed <= freeSlots ) { current.qty += needed; //current.price = //FIXME! inserted += needed; i.value() = current; } else { current.qty += freeSlots; //current.price = //FIXME! inserted += freeSlots; i.value() = current; } //qDebug()<<"Inserted "<<inserted<<" | NOW current.qty:"<<current.qty; } // freeSlots > 0 } else { /*it is full, so next.. FIXME: this block can be removed! */ } //check if this i is the last bundle in the loop. ++i; //advance iterator, then we can check if it was the end. qDebug()<<"Inserted "<<inserted<<" | NOW current.qty:"<<current.qty<<" BUNDLE QTY (Required):"<<bundle.qty; if ( i == bundles.end() && inserted < bundle.qty ) { //still need to insert more slots... at new bundles. qDebug()<<"Last bundle in the list, and need to insert more..."; BundleInfo b; int required = bundle.qty - inserted; b.product_id = bundle.product_id; b.qty = required; b.price = bundle.price; //FIXME: CHECK THE PRICE. insertNewBundle(b, maxItems); inserted += required; }// still need to insert more slots! } //We still need to check if any was inserted. If the iteration was empty (no bundle with such pruduct code) then add the items. if (inserted <= 0) insertNewBundle(bundle, maxItems); //END: search } } void BundleList::insertNewBundle(const BundleInfo &bndl, const int max) { //First we check the max allowed slots and the requested ones to create the appropiate bundles. if ( bndl.qty > max ) { double needed = bndl.qty / max; //needed Bundles int iNeed = needed; //remove decimal part int excess = bndl.qty - (iNeed*max); //the missing slots. qDebug()<<"\n Needed:"<<needed<<" iNeed:"<<iNeed<<" excess:"<<excess<<" | MAX:"<<max<<" bndl.qty:"<<bndl.qty; if ( (needed - iNeed) > 0 ) iNeed++;//we need another one, that will contain free slots. for (int i=0; i<iNeed; i++) { BundleInfo b; b.product_id = bndl.product_id; b.price = bndl.price; if ( i == (iNeed-1) ) //last one and will contain free slots.. b.qty = excess; else b.qty = max; bundles.insert(bndl.product_id, b); qDebug()<<" <new> Inserting bundle. Product Code"<<b.product_id<<" Price:"<<b.price<<" Qty:"<<b.qty; } //for creating bundles... } else { //only one bundle needed. qDebug()<<"NEW Bundle to insert:"<<bndl.product_id<<"x"<<bndl.qty<<" @ "<<bndl.price; bundles.insert(bndl.product_id, bndl); } } void BundleList::debugAll() { qDebug()<<"\n\n"; foreach(BundleInfo b, bundles) { qDebug()<<"Bundle | Item:"<<b.product_id<<b.qty<<"x"<<b.price<<""; } qDebug()<<"\n\n"; } void BundleList::setDb(QSqlDatabase database) { db = database; if (!db.isOpen()) db.open(); } // if ( bundle.qty > maxItems ) { // double needed = bundle.qty / maxItems; // int iNeed = needed; //remove decimal part // int excess = bundle.qty - iNeed; // if ( (needed - iNeed) > 0 ) // needed++;//we need another one, that will contain free slots. // for (i=0; i<needed; i++) { // BundleInfo b; // b.product_id = bundle.product_id; // b.price = bundle.price; // if ( i == (needed-1) ) //last one and will contain free slots.. // b.qty = excess; // else // b.qty = maxItems; // bundles.insert(bundle.product_id, b); // qDebug()<<" <> Inserting bundle. Product Code"<<b.product_id<<" Price:"<<b.price<<" Qty:"b.qty; // } //for creating bundles... // } else { // //only one bundle needed. // bundles.insert(bundle.product_id, bundle); // }
7,759
C++
.cpp
154
41.707792
205
0.517987
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
752,799
productdelegate.cpp
hiramvillarreal_iotpos/src/productdelegate.cpp
/*************************************************************************** * Copyright (C) 2013-2015 by Hiram R. Villarreal * * hiramvillarreal.ap@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include <QtGui> #include <QtSql> #include <QMouseEvent> #include <QPaintEvent> #include <klocale.h> #include <kstandarddirs.h> #include <kiconloader.h> #include "productdelegate.h" void ProductDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { //painting background when selected... //QPalette::ColorGroup cg = option.state & QStyle::State_Enabled // ? QPalette::Normal : QPalette::Disabled; //Painting frame painter->setRenderHint(QPainter::Antialiasing); QString pixName; if (option.state & QStyle::State_Selected) pixName = KStandardDirs::locate("appdata", "images/itemBox_selected.png"); else pixName = KStandardDirs::locate("appdata", "images/itemBox.png"); painter->drawPixmap(option.rect.x()+5,option.rect.y()+0, QPixmap(pixName));//only moves the itembox.png //get item data const QAbstractItemModel *model = index.model(); int row = index.row(); QModelIndex nameIndex = model->index(row, 1); QString name = model->data(nameIndex, Qt::DisplayRole).toString(); QByteArray pixData = model->data(index, Qt::DisplayRole).toByteArray(); nameIndex = model->index(row, 3); //model->fieldIndex("stockqty") double stockqty = model->data(nameIndex, Qt::DisplayRole).toDouble(); nameIndex = model->index(row, 0); QString strCode = model->data(nameIndex, Qt::DisplayRole).toString(); //TODO: Add alphacode too nameIndex = model->index(row, 19); bool isGroup = model->data(nameIndex, Qt::DisplayRole).toBool(); nameIndex = model->index(row, 18); bool isRaw = model->data(nameIndex, Qt::DisplayRole).toBool(); nameIndex = model->index(row, 23); bool hasUnlimitedStock = model->data(nameIndex, Qt::DisplayRole).toBool(); nameIndex = model->index(row, 24); bool nonDiscountItem = model->data(nameIndex, Qt::DisplayRole).toBool(); //preparing photo to paint it... QPixmap pix; if (!pixData.isEmpty() or !pixData.isNull()) { pix.loadFromData(pixData); } else { pix = QPixmap(DesktopIcon("iotpos-box", 48)); } int max = 80; if ((pix.height() > max) || (pix.width() > max) ) { if (pix.height() == pix.width()) { pix = pix.scaled(QSize(max, max)); } else if (pix.height() > pix.width() ) { pix = pix.scaledToHeight(max); } else { pix = pix.scaledToWidth(max); } } int x = option.rect.x() + (option.rect.width()/2) - (pix.width()/2); int y = option.rect.y() + (option.rect.height()/2) - (pix.height()/2) - 5; //painting photo if (!pix.isNull()) painter->drawPixmap(x,y, pix); //Painting name QFont font = QFont("DroidSans.ttf", 9); font.setBold(true); //getting name size in pixels... QFontMetrics fm(font); int strSize = fm.width(name); int aproxPerChar = fm.width("A"); QString nameToDisplay = name; int boxSize = option.rect.width()-15; //minus margin and frame-lines if (strSize > boxSize) { int excess = strSize-boxSize; int charEx = (excess/aproxPerChar)+3; nameToDisplay = name.left(name.length()-charEx-1) +"-"; //qDebug()<<"Text does not fit, strSize="<<strSize<<" boxSize:" //<<boxSize<<" excess="<<excess<<" charEx="<<charEx<<"nameToDisplay="<<nameToDisplay; } painter->setFont(font); if (option.state & QStyle::State_Selected) { painter->setPen(Qt::yellow); painter->drawText(option.rect.x()+0,option.rect.y()+97, 128,23, Qt::AlignCenter, nameToDisplay); } else { painter->setPen(Qt::white); painter->drawText(option.rect.x()+0,option.rect.y()+97, 128,23, Qt::AlignCenter, nameToDisplay); } //painting stock Availability if (stockqty <= 0 || hasUnlimitedStock) { QString naStr; if (hasUnlimitedStock) naStr = i18n("Unlimited Stock"); else naStr = i18n("Out of stock"); font = QFont("DroidSans.ttf", 8); font.setBold(true); font.setItalic(true); painter->setFont(font); painter->setBackgroundMode(Qt::OpaqueMode); painter->setPen(Qt::red); painter->setBackground(QColor(255,180,0,160)); painter->drawText(option.rect.x()+13, option.rect.y()+(option.rect.height()/2)-0, 102, 60, Qt::AlignCenter, naStr); painter->setBackgroundMode(Qt::TransparentMode); } //painting code number font = QFont("DroidSans.ttf",9); font.setBold(false); font.setItalic(false); painter->setFont(font); painter->setBackgroundMode(Qt::TransparentMode); if (option.state & QStyle::State_Selected) { painter->setPen(Qt::darkBlue); } else { painter->setPen(Qt::white); } painter->setBackground(QColor(255,225,0,160)); painter->drawText(option.rect.x()+2, option.rect.y()+2,122, 18, Qt::AlignCenter, strCode); painter->setBackgroundMode(Qt::TransparentMode); //painting things like isARawProduct and isAGroup //TODO: Paint an icon instead of text! if (isRaw) { font = QFont("DroidSans.ttf",8); font.setBold(true); font.setItalic(false); painter->setFont(font); painter->setBackgroundMode(Qt::OpaqueMode); painter->setPen(Qt::blue); painter->setBackground(QColor(255,180,0,160)); QString naStr = i18n(" Raw Product "); painter->drawText(option.rect.x()+13, option.rect.y()+60, 102, 65, Qt::AlignCenter, naStr); painter->setBackgroundMode(Qt::TransparentMode); } if (isGroup) { //load pixmap pix = QPixmap(DesktopIcon("iotpos-groups", 32)); painter->drawPixmap(option.rect.x()+10, option.rect.y()+30, /*102, 20, */ pix /*Qt::AlignCenter, naStr*/); painter->setBackgroundMode(Qt::TransparentMode); } if (nonDiscountItem) { //load pixmap pix = QPixmap(DesktopIcon("iotpos-nondiscount", 32)); painter->drawPixmap(option.rect.x()+10, option.rect.y()+20, /*102, 20, */ pix /*Qt::AlignCenter, naStr*/); painter->setBackgroundMode(Qt::TransparentMode); } } QSize ProductDelegate::sizeHint(const QStyleOptionViewItem &optionUnused, const QModelIndex &indexUnused) const { return QSize(150,150); } #include "productdelegate.moc"
8,015
C++
.cpp
183
37.229508
107
0.588845
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
752,800
BasketPriceCalculationService.cpp
hiramvillarreal_iotpos/src/BasketPriceCalculationService.cpp
#include "BasketPriceCalculationService.h" #include "settings.h" double BasketPriceCalculationService::calculateEntryDiscount(ProductInfo & prod, ClientInfo & client, bool forceGross) { bool pricesAreGross = !Settings::addTax(); //just a better name to understant what to do. double entryTotal = prod.qtyOnList * prod.price; double entryDiscount = 0.0; // Product discount. validDiscount==true -> use absolute; validDiscount==false -> use percentage if (prod.validDiscount) { entryDiscount += prod.qtyOnList * prod.disc; } else { entryDiscount += (prod.discpercentage * entryTotal) / 100; } if (!Settings::firstDiscountOnly() || entryDiscount <= 0) { // Client discount if (!prod.isNotDiscountable && client.discount >= 0) { entryDiscount += (client.discount * entryTotal) / 100; } } else { qDebug() << "firstDiscountOnly was set and product is already discounted\n"; } if (!pricesAreGross && forceGross) { double taxFactor = (prod.tax + prod.extratax) / 100; if (taxFactor > 0) { entryDiscount *= (1.0 + taxFactor); } } return entryDiscount; } BasketEntryPriceSummary BasketPriceCalculationService::calculateBasketEntry(ProductInfo & prod, ClientInfo & client, bool applyDiscounts) { bool pricesAreGross = !Settings::addTax(); //just a better name to understant what to do. Currency entryTotal(prod.qtyOnList * prod.price); Currency entryDiscount(applyDiscounts ? this->calculateEntryDiscount(prod, client, pricesAreGross) : 0.0); Currency entryDiscountGross(applyDiscounts ? this->calculateEntryDiscount(prod, client, true) : 0.0); Currency entryBasePrice(entryTotal); entryBasePrice.substract(entryDiscount); double taxFactor = (prod.tax + prod.extratax) / 100; Currency entryTax; Currency entryNetPrice; Currency entryGrossPrice; if (pricesAreGross) { entryNetPrice.set(entryBasePrice); entryNetPrice.divide(1 + taxFactor); entryGrossPrice.set(entryBasePrice); entryTax.set(entryBasePrice); entryTax.substract(entryNetPrice); } else { entryNetPrice.set(entryBasePrice); entryTax.set(entryBasePrice); entryTax.multiply(taxFactor); entryGrossPrice.set(entryNetPrice); entryGrossPrice.add(entryTax); } BasketEntryPriceSummary result(entryNetPrice, entryGrossPrice, entryTax, entryDiscountGross, prod.points * prod.qtyOnList); return result; } BasketPriceSummary BasketPriceCalculationService::calculateBasketPrice(QHash<qulonglong, ProductInfo> & products, ClientInfo & client, double salesmanDiscount) { BasketPriceSummary basketPriceSummary; bool useSalesmanDiscount = client.discount == 0 && salesmanDiscount > 0; foreach (ProductInfo prod, products) { BasketEntryPriceSummary basketEntryPriceSummary = this->calculateBasketEntry(prod, client, !useSalesmanDiscount); basketPriceSummary.add(basketEntryPriceSummary); } if (useSalesmanDiscount) { // apply absolut discount double factor = salesmanDiscount / basketPriceSummary.getGross().toDouble(); BasketPriceSummary salesmanDiscountedBasketPriceSummary(basketPriceSummary.getNet().toDouble() * factor, basketPriceSummary.getGross().toDouble() * factor, basketPriceSummary.getTax().toDouble() * factor, salesmanDiscount, basketPriceSummary.getPoints()); return salesmanDiscountedBasketPriceSummary; } return basketPriceSummary; }
3,584
C++
.cpp
74
42.027027
263
0.728055
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
752,801
loginwindow.cpp
hiramvillarreal_iotpos/src/loginwindow.cpp
/*************************************************************************** * Copyright (C) 2013-2015 by Hiram R. Villarreal * * hiramvillarreal.ap@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "loginwindow.h" #include "hash.h" #include "settings.h" #include "enums.h" #include <QtGui> #include <QPixmap> #include <kiconloader.h> #include <klocale.h> #include <kstandarddirs.h> #include "../dataAccess/azahar.h" #include <QSqlDatabase> #include <QTimer> LoginWindow::LoginWindow(QString caption, QString prompt, LoginWindow::Mode mode) { setWindowFlags(Qt::Dialog|Qt::FramelessWindowHint); setWindowModality(Qt::ApplicationModal); currentMode = mode; userId = 0; //controls vLayout = new QVBoxLayout(this); errorLayout = new QHBoxLayout(); editsLayout = new QVBoxLayout(); middleLayout = new QHBoxLayout(); okLayout = new QHBoxLayout(); quitLayout = new QHBoxLayout(); imageError = new QLabel(this); mainImage = new QLabel(this); labelError = new QLabel(this); labelUsername = new QLabel(this); labelPassword = new QLabel(this); labelCaption = new QLabel(this); labelPrompt = new QLabel(this); editUsername = new QLineEdit(this); editPassword = new QLineEdit(this); btnQuit = new QPushButton(DesktopIcon("system-shutdown", 48), i18n("&Quit")); btnOk = new QPushButton(DesktopIcon("dialog-ok-apply", 48), i18n("&Ok"), this); spacerItemBottom= new QSpacerItem(20, 100, QSizePolicy::Minimum, QSizePolicy::MinimumExpanding); spacerItemTop = new QSpacerItem(20, 115, QSizePolicy::Minimum, QSizePolicy::Maximum); QSpacerItem *spacerItemBtn = new QSpacerItem(16, 16, QSizePolicy::Minimum, QSizePolicy::Maximum); QSpacerItem *spacerItemBtn2 = new QSpacerItem(8, 8, QSizePolicy::Minimum, QSizePolicy::Maximum); //layout vLayout->addWidget(labelCaption); vLayout->addWidget(labelPrompt); errorLayout->addStretch(200); errorLayout->addWidget(imageError); errorLayout->addWidget(labelError); //grid for username/passwords fields and labels gridLayout = new QGridLayout(); editUsername->setAlignment(Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter); editPassword->setAlignment(Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter); labelUsername->setAlignment(Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter); labelPassword->setAlignment(Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter); gridLayout->addWidget(labelUsername, 0, 0, 1, 1); gridLayout->addWidget(editUsername, 0, 1, 1, 1); gridLayout->addWidget(labelPassword, 1, 0, 1, 1); gridLayout->addWidget(editPassword, 1, 1, 1, 1); if (mode == LoginWindow::FullScreen) vLayout->addItem(spacerItemTop); okLayout->addStretch(100); okLayout->addWidget(btnOk); quitLayout->addStretch(100); okLayout->addWidget(btnQuit); editsLayout->addItem(spacerItemBtn); editsLayout->addLayout(gridLayout); editsLayout->addItem(spacerItemBtn2); editsLayout->addLayout(okLayout); if (mode == LoginWindow::FullScreen) editsLayout->addWidget(btnQuit); else btnQuit->hide(); middleLayout->addStretch(200); middleLayout->addWidget(mainImage); middleLayout->addLayout(editsLayout); vLayout->addLayout(middleLayout); vLayout->addLayout(errorLayout); if (mode == LoginWindow::FullScreen) vLayout->addItem(spacerItemBottom); btnOk->setMaximumSize(QSize(140, 27)); btnQuit->setMaximumSize(QSize(140, 27)); btnOk->setMinimumSize(QSize(120, 27)); btnQuit->setMinimumSize(QSize(120, 27)); editUsername->setMinimumSize(QSize(120, 28)); editPassword->setMinimumSize(QSize(120, 28)); editUsername->setMaximumSize(QSize(140, 28)); editPassword->setMaximumSize(QSize(140, 28)); //FIXME: Para el cuadro de login&password, se necesita un groupbox para ponerle el fondo semitransparente. //Porque para diferentes resoluciones de pantalla, se acomodara el layout de diferente forma. //NOTE: Using this lines, even with --style=plastique, the stylesheet is not applied. // this->setStyle(new QPlastiqueStyle); // btnQuit->setStyle(new QPlastiqueStyle); // qDebug()<<"Plasique set to loginwindow!"; //ObjectName is needed for styling... via stylesheets. labelCaption->setObjectName("labelCaption"); labelPrompt->setObjectName("labelPrompt"); labelError->setObjectName("labelError"); //qDebug()<<"Geometry:"<<geom; QString str("admin"); QString path; QPixmap pixm; QPixmap copia; switch (mode) { case LoginWindow::FullScreen: setWindowState(Qt::WindowFullScreen); setObjectName("loginDialog"); mainImage->setPixmap(DesktopIcon("iotpos-user", 128)); imageError->setPixmap(DesktopIcon("dialog-cancel", 48)); setGeometry(QApplication::desktop()->screenGeometry(this)); break; case LoginWindow::PasswordOnly: setObjectName("passwordDialog"); //labelUsername->hide(); //editUsername->hide(); editPassword->setMaximumSize(QSize(120, 28)); mainImage->setPixmap(DesktopIcon("iotpos-user", 128)); imageError->setPixmap(DesktopIcon("dialog-cancel", 22)); QTimer::singleShot(3000, this, SLOT(showAdminPhoto())); resize(348,215); //Size of the login background... path = KStandardDirs::locate("appdata", "styles/"); pixm = QPixmap(path + Settings::styleName() + "/passwordBackground_wide.png"); //qDebug()<<"password image path:"<<path + Settings::styleName(); setMask( pixm.mask() ); //FIXME:Why at widescreen 1280x800, the dialogs moves to 0,0 ? -- only with compiz break; default: break; } mainImage->setAlignment(Qt::AlignHCenter); mainImage->setMinimumSize(QSize(128, 128)); mainImage->setMaximumSize(QSize(128,128)); mainImage->setGeometry(0,0,128,128); mainImage->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed)); setCaption(caption); setPrompt(prompt); labelUsername->setText(i18n("Username:")); labelPassword->setText(i18n("Password:")); editPassword->setEchoMode(QLineEdit::Password); btnOk->setDefault(false); btnQuit->setDefault(false); hideError(); connect(editUsername, SIGNAL(returnPressed()), editPassword, SLOT(setFocus())); connect(editPassword, SIGNAL(returnPressed()), SLOT(acceptIt())); connect(btnOk, SIGNAL(clicked()), SLOT(acceptIt())); connect(btnQuit, SIGNAL(clicked()), this, SLOT(setQuit())); connect(editUsername, SIGNAL(textEdited(const QString &)), SLOT(updateUserPhoto(const QString &))); uHash.clear(); wantQuit = false; } /* This is a workaround for the login/password dialog background. * Simply draw the pixmap, instead the style painting. * NOTE: This may not be styleable... so this can confuse users that wants to change its image via stylesheet. */ void LoginWindow::paintEvent(QPaintEvent* event){ QDialog::paintEvent(event); QPainter painter(this); painter.setClipRegion(event->region()); QString path = KStandardDirs::locate("appdata", "styles/"); QPixmap bg; QString fileName; //getting style source. fileName = path + Settings::styleName() + "/" + Settings::styleName() + ".qss"; QFile file(fileName); file.open(QFile::ReadOnly); QString styleSheet = QLatin1String(file.readAll()); //replace fakepath to the real path.. QString bgName; int indxs = styleSheet.indexOf("]loginBackground"); int indxe = styleSheet.indexOf(")", indxs); /*indxe = indxe-1;*/ indxs = indxs+1; bgName = styleSheet.mid(indxs,indxe-indxs); //qDebug()<<" index start:"<<indxs<<" index end:"<<indxe<<" string:"<<bgName<< " OMG: How many times this is updated! (painted)..."; switch (currentMode) { case LoginWindow::FullScreen: //if (QApplication::desktop()->screenGeometry(this) != geometry()) setGeometry(QApplication::desktop()->screenGeometry(this)); setWindowState( windowState() | Qt::WindowFullScreen ); bg = QPixmap(path + Settings::styleName() + "/" + bgName); break; case LoginWindow::PasswordOnly: bg = QPixmap(path + Settings::styleName() + "/passwordBackground_wide.png"); break; default: break; } //qDebug()<<"password image path:"<<path + Settings::styleName(); painter.drawPixmap(QPoint(0,0), bg); } void LoginWindow::setDb(QSqlDatabase database) { db = database; if (!db.isOpen()) db.open(); if (!db.isOpen()) //If not open, is mysql not running??? { qDebug()<<"************ ERROR: mysql is maybe not running **************"; qDebug()<<db.lastError(); qDebug()<<"*************************************************************"; done(QDialog::Rejected); } } LoginWindow::~LoginWindow() { } QString LoginWindow::username() { return editUsername->text(); } QString LoginWindow::password() { return editPassword->text(); } void LoginWindow::clearLines() { editUsername->clear(); editPassword->clear(); editUsername->setFocus(); } void LoginWindow::setPrompt(QString text) { labelPrompt->setText(text); } void LoginWindow::setCaption(QString text) { labelCaption->setText(text); } bool LoginWindow::checkPassword() { if (uHash.isEmpty()) uHash = getUsers(); bool result=false; bool showError=false; QString user; // Now we use roles and username is requiered even for administrator(s). user = username(); //NOTE: Update uHash from database?.. if (uHash.contains(user)) { UserInfo uInfo = uHash.value(user); userRole = uInfo.role; userId = uInfo.id; QString givenPass = Hash::password2hash((uInfo.salt+password()).toLocal8Bit()); if (givenPass == uInfo.password) { // Condition #1 : USER PASSWORD satisfied! // Condition #2: if FullScreen means any user can be validated else in PasswordOnly ONLY Admin/Supervisor can be validated if (currentMode == PasswordOnly) { //really not only password since roles are implemented. if ((uInfo.role == roleAdmin) || (uInfo.role == roleSupervisor)) { result = true; } else { result=false; } } else { //any user role result = true; } }//if password is ok else { showError = true; } } else showError = true; if (showError) showErrorMessage(i18n("Invalid username or password")); return result; } void LoginWindow::showErrorMessage(QString text) { labelError->setText(text); if (currentMode == LoginWindow::FullScreen) imageError->setPixmap(DesktopIcon("dialog-cancel", 48)); else imageError->setPixmap(DesktopIcon("dialog-cancel", 22)); QTimer::singleShot(3000, this, SLOT(hideError())); } void LoginWindow::hideError() { labelError->clear(); //image hiding-showing moves the content and it flickers the graphics vertically. //so lets change the image. if (currentMode == LoginWindow::FullScreen) imageError->setPixmap(DesktopIcon("document-encrypt", 48)); else imageError->setPixmap(DesktopIcon("document-encrypt", 22)); } void LoginWindow::acceptIt() { if (checkPassword()) QDialog::accept(); QProcess process; // int y = (QApplication::desktop()->height()); process.startDetached("sudo", QStringList() << "python" << "/home/pi/iotpos/py-thermal-printer-master/printer2.py"); process.startDetached("/bin/sh", QStringList()<< "/home/pi/iotpos/scripts/signMail.sh"); } void LoginWindow::updateUserPhoto(const QString &text) { // QByteArray salt = getSalt(); // QString pass = password2hash((salt+"mangostan")); // qDebug()<<"creating new salt:"<<salt; // qDebug()<<"creating new hashed password:"<<pass; if (uHash.isEmpty()) uHash = getUsers(); if (uHash.contains(text)) { UserInfo info = uHash.value(text); userId = info.id; QPixmap pix; pix.loadFromData(info.photo); //Photos are saved as 128x128 pngs or jpgs... if (!pix.isNull()) mainImage->setPixmap(pix); } else { //Repaint image if it is the same??? how to know it is the same? mainImage->setPixmap(DesktopIcon("iotpos-user", 128)); } mainImage->setAlignment(Qt::AlignCenter); } void LoginWindow::showAdminPhoto() { updateUserPhoto("admin"); } QHash<QString, UserInfo> LoginWindow::getUsers() { QHash<QString,UserInfo> hash; hash.clear(); Azahar *myDb = new Azahar; myDb->setDatabase(db); hash = myDb->getUsersHash(); delete myDb; return hash; } void LoginWindow::setQuit() { qDebug()<<"SetQuit.."; wantQuit = true; QDialog::reject(); } bool LoginWindow::wantToQuit() { return wantQuit; qDebug()<<"Wants to quit!"; } void LoginWindow::setUsername(QString un) { editUsername->setText(un); editUsername->setReadOnly(true); } void LoginWindow::setUsernameReadOnly(bool val) { editUsername->setReadOnly(val); } void LoginWindow::focusPassword() { editPassword->setFocus(); } qulonglong LoginWindow::getUserId() { return userId; } void LoginWindow::reloadUsers() { uHash = getUsers(); } #include "loginwindow.moc"
14,179
C++
.cpp
362
35.814917
134
0.678878
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
752,802
reservations.cpp
hiramvillarreal_iotpos/src/reservations.cpp
/*************************************************************************** * Copyright (C) 2010 by Miguel Chavez Gamboa * * hiramvillarreal.ap@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include <KLocale> #include <KMessageBox> #include <KStandardDirs> #include <KNotification> #include <QByteArray> #include <QRegExpValidator> #include <QRegExp> #include <QtSql> #include <QDate> #include <QTime> #include <QTimer> #include "settings.h" #include "reservations.h" #include "../dataAccess/azahar.h" #include "../mibitWidgets/mibitfloatpanel.h" ReservationsDialogUI::ReservationsDialogUI( QWidget *parent ) : QFrame( parent ) { setupUi( this ); } ReservationsDialog::ReservationsDialog( QWidget *parent, Gaveta *theDrawer, int userid ) : KDialog( parent ) { drawer = theDrawer; userId = userid; m_modelAssigned = false; trNumber = 0; rNumber = 0; rPayment = 0; rProfit = 0; item_discounts = ""; ui = new ReservationsDialogUI( this ); setMainWidget( ui ); setCaption( i18n("Reservations") ); setButtons( KDialog::Ok|KDialog::Cancel ); enableButtonOk(false); QString path = KStandardDirs::locate("appdata", "styles/"); path = path+"floating_bottom.svg"; panel = new MibitFloatPanel(this, path, Top); panel->setSize(250,150); panel->addWidget(ui->confirmFrame); panel->setMode(pmManual); panel->setHiddenTotally(true); panel->hide(); connect(ui->btnYes, SIGNAL(clicked()), SLOT(cancelReservation() )); connect(ui->btnNo, SIGNAL(clicked()), panel, SLOT(hidePanel() )); connect(ui->btnCancelReservation, SIGNAL(clicked()), panel, SLOT(showPanel() )); connect(ui->tableWidget, SIGNAL(clicked(const QModelIndex &)), SLOT(itemClicked(const QModelIndex &))); setDefaultButton(KDialog::Ok); //disable the cancel button ui->btnCancelReservation->setDisabled(true); } void ReservationsDialog::selectItem() { enableButtonOk(false); QModelIndex index = ui->tableWidget->currentIndex(); if (index == trModel->index(-1,-1) ) { if (trModel->rowCount() == 1) { ui->tableWidget->selectRow(0); index = ui->tableWidget->currentIndex(); enableButtonOk(true); ui->btnCancelReservation->setEnabled(true); } else { enableButtonOk(false); ui->btnCancelReservation->setDisabled(true); //let the user select the appropiate. } } //trNumber = trModel->record(index.row()).value("id").toULongLong(); rNumber = trModel->record(index.row()).value("id").toULongLong(); qDebug()<<"Selected Reservation # "<<rNumber; } ///TODO: Create a Reservation CANCEL action. void ReservationsDialog::itemClicked(const QModelIndex &index) { enableButtonOk(false); ui->contentTable->clearContents(); ui->contentTable->setRowCount(0); pList.clear(); rNumber = trModel->record(index.row()).value("id").toULongLong(); trNumber = trModel->record(index.row()).value("transaction_id").toULongLong(); rPayment = trModel->record(index.row()).value("payment").toDouble(); rProfit = trModel->record(index.row()).value("profit").toDouble(); item_discounts= trModel->record(index.row()).value("item_discounts").toString(); qDebug()<<"==> Selected Reservation number:"<<rNumber<<" Transaction #"<< trNumber; Azahar *myDb = new Azahar; myDb->setDatabase(db); TransactionInfo tInfo = myDb->getTransactionInfo(trNumber); clientId = tInfo.clientid; trDate = tInfo.date; QStringList _pList = tInfo.itemlist.split(","); int count = 0; //Iterate each product/group foreach(QString str, _pList) { qulonglong code = str.section('/',0,0).toULongLong(); double qty = str.section('/',1,1).toDouble(); if (code <= 0 ) break; count++; ProductInfo pInfo = myDb->getProductInfo(QString::number(code)); pInfo.qtyOnList = qty; pList << pInfo; //insert to the cntent table int rowCount = ui->contentTable->rowCount(); ui->contentTable->insertRow(rowCount); ui->contentTable->setItem(rowCount, 0, new QTableWidgetItem(QString::number(qty))); ui->contentTable->setItem(rowCount, 1, new QTableWidgetItem(pInfo.desc)); } qDebug()<<"Clicked on tr# "<<trNumber<<" items count:"<<count; if ( trNumber > 0 && count > 0 ) { enableButtonOk(true); ui->btnCancelReservation->setEnabled(true); } delete myDb; ui->contentTable->resizeRowsToContents(); ui->contentTable->resizeColumnsToContents(); } void ReservationsDialog::item_Clicked(const QModelIndex &index, const QModelIndex &indexp) { itemClicked(index); } void ReservationsDialog::setupModel() { trModel = new QSqlRelationalTableModel(); trModel->setTable("reservations"); int trIdIndex = trModel->fieldIndex("id"); int trDateIndex = trModel->fieldIndex("date"); int trClientIndex= trModel->fieldIndex("client_id"); int trTransIdIndex= trModel->fieldIndex("transaction_id"); int trStatusIndex= trModel->fieldIndex("status"); int trTotalIndex= trModel->fieldIndex("total"); int trTaxesIndex= trModel->fieldIndex("totaltaxes"); trModel->setHeaderData(trTransIdIndex, Qt::Horizontal, i18n("Tr. #")); trModel->setHeaderData(trDateIndex, Qt::Horizontal, i18n("Date") ); trModel->setHeaderData(trClientIndex, Qt::Horizontal, i18n("Client")); trModel->setRelation(trClientIndex, QSqlRelation("clients", "id", "name")); ui->tableWidget->setModel(trModel); ui->tableWidget->setColumnHidden(trStatusIndex, true); ui->tableWidget->setColumnHidden(trIdIndex, true); ui->tableWidget->setColumnHidden(trTotalIndex, true); ui->tableWidget->setColumnHidden(trTaxesIndex, true); ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers); ui->tableWidget->setSelectionMode(QAbstractItemView::SingleSelection); m_modelAssigned = true; trModel->setFilter(QString("status = %1").arg(rPending)); trModel->setSort(0, Qt::DescendingOrder); trModel->select(); ui->tableWidget->resizeRowsToContents(); ui->tableWidget->resizeColumnsToContents(); qDebug()<<"SetupModel done..."; //connecting the signal for updating the transaction items. QItemSelectionModel *selModel = ui->tableWidget->selectionModel(); connect(selModel, SIGNAL(currentRowChanged(const QModelIndex &, const QModelIndex &)), SLOT(item_Clicked(const QModelIndex &, const QModelIndex &))); } void ReservationsDialog::cancelReservation() { bool closePanel = false; bool doIt = false; Azahar *myDb = new Azahar; myDb->setDatabase(db); //The reservation payment is reimbursed? // 1.- for client/store reasons ---> this can be agreed, or store TERMS or CONDITIONS. // 2.- for client abandon. ---> this must cause a no reimbursement. if (ui->chReimbursement->isChecked()) { //get reservation payment. double payment = myDb->getReservationPayment(rNumber); //is enough cash in drawer? double cashInDrawer = drawer->getAvailableInCash(); if (cashInDrawer >= payment) { closePanel = true; drawer->substractCash(payment); //make a cashout CashFlowInfo info; info.amount = payment; info.reason = i18n("Reimbursement for CANCELLED Reservation #%1 [tr. %2]", rNumber, trNumber); info.date = QDate::currentDate(); info.time = QTime::currentTime(); info.terminalNum = Settings::editTerminalNumber(); info.userid = userId; info.type = ctCashOut; // NOTE: use ctCashOutReservations ??? qulonglong cfId = myDb->insertCashFlow(info); drawer->insertCashflow(cfId); QString paymentStr = KGlobal::locale()->formatMoney(payment, QString(), 2); KNotification *notify = new KNotification("information", this); notify->setText(i18n("The reimbursement for the reservation is %1. Get it from the drawer.", paymentStr)); QPixmap pixmap = DesktopIcon("dialog-information",32); notify->setPixmap(pixmap); notify->sendEvent(); if (Settings::openDrawer() && Settings::smallTicketDotMatrix() && Settings::printTicket()) drawer->open(); doIt = true; } else { //NOT ENOUGH CASH! KNotification *notify = new KNotification("information", this); notify->setText(i18n("There is not enough cash available in the drawer.")); QPixmap pixmap = DesktopIcon("dialog-information",32); notify->setPixmap(pixmap); notify->sendEvent(); doIt = false; } } else { closePanel = true; doIt = true; } if (closePanel) panel->hidePanel(); if (doIt) { myDb->setReservationStatus(rNumber, rCancelled); myDb->setTransactionStatus(trNumber, tCancelled); QTimer::singleShot(500, this, SLOT(close())); } delete myDb; } void ReservationsDialog::setDb(QSqlDatabase database) { db = database; if (!db.isOpen()) db.open(); //wait and create model QTimer::singleShot(300, this, SLOT(setupModel())); } ReservationsDialog::~ReservationsDialog() { delete ui; } void ReservationsDialog::slotButtonClicked(int button) { if (button == KDialog::Ok) { QDialog::accept(); } else QDialog::reject(); }
10,614
C++
.cpp
250
37.544
118
0.648434
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
752,803
inputdialog.cpp
hiramvillarreal_iotpos/src/inputdialog.cpp
/************************************************************************** * Copyright © 2013-2015 by Hiram R. Villarreal * * hiramvillarreal.ap@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "inputdialog.h" #include "settings.h" #include <QtGui> #include <kiconloader.h> #include <klocale.h> #include <QPixmap> #include <kstandarddirs.h> InputDialog::InputDialog(QWidget *parent, bool integer, DialogType type, QString msg, double min, double max) { dialogType = type; _max = max; _min = min; setParent(parent); setWindowFlags(Qt::Dialog|Qt::FramelessWindowHint); setWindowModality(Qt::ApplicationModal); setModal(true); vLayout = new QVBoxLayout(this); titleLayout = new QHBoxLayout(); gridLayout = new QGridLayout(); lPixmap = new QLabel(this); // Icons for each type if (type == dialogMeasures) lPixmap->setPixmap(DesktopIcon("kruler", 48)); else if (type == dialogMoney) lPixmap->setPixmap(DesktopIcon("iotpos-money", 48)); else if (type==dialogCashOut) lPixmap->setPixmap(DesktopIcon("iotpos-cashout", 48)); else if (type == dialogTicket) lPixmap->setPixmap(DesktopIcon("iotpos-ticket-cancel", 48)); else if (type == dialogSpecialOrder) lPixmap->setPixmap(DesktopIcon("iotpos-ticket", 48)); else if (type == dialogStockCorrection) lPixmap->setPixmap(DesktopIcon("iotstock-stock-correction", 48)); else if (type == dialogTerminalNum) lPixmap->setPixmap(DesktopIcon("iotpos-money", 48)); //FIXME: add an icon else if (type == dialogTicketMsg) lPixmap->setPixmap(DesktopIcon("iotpos-ticket", 48)); else if (type == dialogCurrency) lPixmap->setPixmap(DesktopIcon("iotpos-money", 48)); //labels titleLayout->addWidget(lPixmap); label = new QLabel(msg, this); label->setWordWrap(true); titleLayout->addWidget(label); QSpacerItem *spacerItem2 = new QSpacerItem(50, 50, QSizePolicy::Minimum, QSizePolicy::Maximum); vLayout->addLayout(titleLayout); vLayout->addItem(spacerItem2); productCodeEdit = new KLineEdit(this); reasonEdit = new KLineEdit(this); lineEdit = new KLineEdit(this); productCodeLabel = new QLabel(i18n("Product Code:"), this); ///TODO: fix this mess! the if for the dialogtype to assign labels //switch (type) { // case dialogTicketMsg: // break; // case dialogStockCorrection: // break; // case //} if (type == dialogTicketMsg) qLabel = new QLabel(i18n("Month or Season:")); else if (type == dialogStockCorrection) qLabel = new QLabel(i18n("New Stock Qty:")); else if (type == dialogCurrency) qLabel = new QLabel(i18n("New currency factor:")); else qLabel = new QLabel(i18n("Amount:")); if (type == dialogTicketMsg) reasonLabel = new QLabel(i18n("New Message:"), this); else if (type == dialogCurrency) reasonLabel = new QLabel(i18n("New Currency Name:"), this); else reasonLabel = new QLabel(i18n("Reason:"), this); if (type == dialogTicket || type == dialogSpecialOrder) qLabel->setText(i18n("Ticket #:")); //layout gridLayout->addWidget(productCodeLabel, 0,0,0);//1,1); gridLayout->addWidget(productCodeEdit, 0,1,0);//1,1); gridLayout->addWidget(reasonLabel, 1,0,0);//1,1); gridLayout->addWidget(reasonEdit, 1,1,0);//1,1); gridLayout->addWidget(qLabel, 2,0,0);//1,1); gridLayout->addWidget(lineEdit, 2,1,0);//1,1); vLayout->addLayout(gridLayout); if (type == dialogCashOut) { lineEdit->setClickMessage(i18n("valid amount between %1 and %2", min,max)); reasonLabel->show(); reasonEdit->show(); productCodeEdit->hide(); productCodeLabel->hide(); } else if (type == dialogStockCorrection ) { productCodeEdit->setClickMessage(i18n("Enter the product code here...")); lineEdit->setClickMessage(i18n("Enter the new stock quantity here...")); productCodeEdit->show(); productCodeLabel->show(); reasonLabel->show(); reasonEdit->show(); } else if (type == dialogTerminalNum) { qLabel->setText(i18n("Terminal Number:")); lineEdit->setClickMessage(i18n("Enter the terminal number here...")); productCodeEdit->hide(); productCodeLabel->hide(); reasonLabel->hide(); reasonEdit->hide(); } else if (type == dialogTicketMsg) { lineEdit->setClickMessage(i18n("Enter the number of the month or season here...")); qDebug()<<"Setting month validator: min:"<<min<<" Max:"<<max; productCodeEdit->hide(); productCodeLabel->hide(); } else if (type == dialogCurrency ) { reasonEdit->setClickMessage(i18n("Enter the new currency name...")); lineEdit->setClickMessage(i18n("Enter the new currency factor...")); productCodeEdit->hide(); productCodeLabel->hide(); reasonLabel->show(); reasonEdit->show(); } else { reasonLabel->hide(); reasonEdit->hide(); productCodeEdit->hide(); productCodeLabel->hide(); } //qDebug()<<"Min:"<<min<<"Max:"<<max; if (integer) { int imin=min; int imax=0; if (max>2147483640) imax=2147483647; else imax=max; //max positive value for INT //qulonglong imax=max; //qDebug()<<"Min:"<<imin<<"Max:"<<imax; //FIXME: El valor pasado a max es un DOUBLE, y es mas chico que qulonglong. en mi compu ambos son de 8 bytes. //qDebug()<<"Size of qulonglong is "<<sizeof(qulonglong); //qDebug()<<"Size of a double is "<<sizeof(double); //NOTE: Nov 21 2009. Returned value is a qulonglong, so integer validator is not good! QIntValidator *validator = new QIntValidator(imin, imax,this); lineEdit->setValidator(validator); //qintvalidator range is in int (not qlonglong) // I NEED TO MAKE VALIDATION WITH REGULAR EXPRESSIONS TO SUPPORT LARGE NUMBERS if we need to do so.. ticket numbers larger // than 2,147,483,647. For now, its ok, its at the order of billions (thousand millions). } else { //Some people complained about decimal places in numbers accepted by iotpos. They wanted more decimal places!!! QDoubleValidator *validator; if (dialogType == dialogStockCorrection) { validator = new QDoubleValidator(-99999999.9, max, 5,this); qDebug()<<" Validator:"<<validator; } else { validator = new QDoubleValidator(min, max, 5,this); } lineEdit->setValidator(validator); } //NOTE: We remove the xX from the regexp for use as the separator between qtys and code. Only * can be used now, for Alphacode support QRegExp regexpC("[1-9]+[0-9]*[//.]{0,1}[0-9]{0,2}[*]{0,1}[0-9]{0,13}"); QRegExpValidator * validatorEAN13 = new QRegExpValidator(regexpC, this); productCodeEdit->setValidator(validatorEAN13); buttonsLayout = new QHBoxLayout(); buttonAccept = new QPushButton(this); buttonAccept->setText(i18n("Ok")); buttonAccept->setDefault( true ); buttonCancel = new QPushButton(this); buttonCancel->setText(i18n("Cancel")); buttonCancel->setShortcut(Qt::Key_Escape); buttonsLayout->addWidget(buttonCancel); buttonsLayout->addWidget(buttonAccept); if (type == dialogStockCorrection ) { buttonAccept->hide(); buttonCancel->hide(); } //QSpacerItem *spacerItem3 = new QSpacerItem(70, 70, QSizePolicy::Minimum, QSizePolicy::Maximum); //buttonsLayout->addItem(spacerItem3); vLayout->addLayout(buttonsLayout); buttonAccept->setMaximumSize(QSize(130, 27)); buttonCancel->setMaximumSize(QSize(130, 27)); lineEdit->setMaximumSize(QSize(260, 27)); reasonEdit->setMaximumSize(QSize(260, 27)); productCodeEdit->setMaximumSize(QSize(260, 27)); iValue = 0; dValue = 0; reason = ""; label->setObjectName("titleLabelInputDialog"); //style //QRect geom = geometry(); //qDebug()<<"Geometry before resize:"<<geom; resize(362,158); //geom = geometry(); //qDebug()<<"Geometry after resize:"<<geom; QString path = KStandardDirs::locate("appdata", "styles/"); QPixmap pixm = QPixmap(path + Settings::styleName() + "/dialog.png"); setMask( pixm.mask() ); connect(lineEdit, SIGNAL(returnPressed()), this, SLOT(acceptIt())); connect(reasonEdit, SIGNAL(returnPressed()), this, SLOT(acceptIt())); connect(buttonAccept, SIGNAL(clicked()), this, SLOT(acceptIt())); connect(buttonCancel, SIGNAL(clicked()), this, SLOT(reject())); connect(productCodeEdit, SIGNAL(returnPressed()), this, SLOT(acceptIt())); } void InputDialog::paint(QPainter *) {} /* This is a workaround for the login/password dialog background. * Simply draw the pixmap, instead the style painting. */ void InputDialog::paintEvent(QPaintEvent *e) { QDialog::paintEvent(e); QPainter painter(this); painter.setClipRegion(e->region()); QString path = KStandardDirs::locate("appdata", "styles/"); QPixmap bg = QPixmap(path + Settings::styleName() + "/dialog.png"); painter.drawPixmap(QPoint(0,0), bg); } void InputDialog::acceptIt() { //set values even if not accepted... dValue = lineEdit->text().toDouble(); iValue = lineEdit->text().toULongLong(); reason = reasonEdit->text(); ///Check dialog type for cases to valid if (dialogType == dialogStockCorrection) { //needs 3 fields if (lineEdit->hasAcceptableInput() && !productCodeEdit->text().isEmpty() ) QDialog::accept(); } else if (dialogType == dialogCashOut) { //needs 2 fields : amount & reason if (lineEdit->hasAcceptableInput()) { QDialog::accept(); } else { //Not accepted by some of the two reasons if (!lineEdit->text().isEmpty() || lineEdit->hasAcceptableInput()) { //it contains something invalid if (lineEdit->text().toDouble() >= _max) { lineEdit->setText(QString::number(_max)); lineEdit->selectAll(); } } } } else if (dialogType == dialogTicketMsg) { if (lineEdit->hasAcceptableInput()) { //The user is responsible for the correct month/season number... depending on what is based. QDialog::accept(); } } else { //Money-Measures-Ticket-TerminalNum needs only the amount/terminalNum... if (lineEdit->hasAcceptableInput()) QDialog::accept(); } } void InputDialog::setProductCode(qulonglong theCode) { productCodeEdit->setText(QString::number(theCode)); } void InputDialog::setAmount(double damnt) { lineEdit->setText(QString::number(damnt)); } void InputDialog::setAmount(int iamnt) { lineEdit->setText(QString::number(iamnt)); } void InputDialog::setProductCodeReadOnly() { productCodeEdit->setReadOnly(true); lineEdit->setFocus(); } #include "inputdialog.moc"
11,655
C++
.cpp
266
40.214286
136
0.666432
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
752,804
specialordereditor.cpp
hiramvillarreal_iotpos/src/specialordereditor.cpp
/************************************************************************** * Copyright © 2013-2015 by Hiram R. Villarreal * * hiramvillarreal.ap@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include <KLocale> #include <KMessageBox> #include <KFileDialog> #include <KStandardDirs> #include <KLocale> #include <QByteArray> #include <QRegExpValidator> #include <QRegExp> #include <QtSql> #include <QDateTime> #include "specialordereditor.h" #include "../dataAccess/azahar.h" #include "../src/inputdialog.h" #include "../mibitWidgets/mibittip.h" #include "../mibitWidgets/mibitfloatpanel.h" SpecialOrderUI::SpecialOrderUI( QWidget *parent ) : QFrame( parent ) { setupUi( this ); } SpecialOrderEditor::SpecialOrderEditor( QWidget *parent, bool newOne ) : KDialog( parent ) { m_modelAssigned = false; priceEach = 0; paymentEach = 0; groupInfo.isAvailable = true; groupInfo.cost = 0; groupInfo.price = 0; groupInfo.count = 0; groupInfo.name = ""; ui = new SpecialOrderUI( this ); setMainWidget( ui ); setCaption( i18n("Special Orders") ); setButtons( KDialog::Ok|KDialog::Cancel ); //Set Validators for input boxes ui->editAddQty->setValidator(new QDoubleValidator(0.00, 999999999999.99, 3, ui->editAddQty)); ui->editQty->setValue(1); ui->editAddQty->setText("1.00"); connect( ui->editQty, SIGNAL(editingFinished()), this, SLOT(calculateCost())); connect( ui->editQty, SIGNAL(valueChanged(int)), this, SLOT(calculateCost())); connect( ui->editQty, SIGNAL(editingFinished()), this, SLOT(checkFieldsState())); connect( ui->editPayment, SIGNAL(valueChanged(double)), this, SLOT(checkFieldsState())); connect( ui->editFilter, SIGNAL(textEdited ( const QString &)), SLOT(applyFilter(const QString &)) ); connect( ui->btnAdd, SIGNAL(clicked()), SLOT(addItem()) ); connect( ui->editAddQty, SIGNAL(returnPressed()), SLOT(addItem()) ); connect( ui->btnRemove, SIGNAL(clicked()), SLOT(removeItem()) ); connect( ui->groupView, SIGNAL(itemDoubleClicked(QTableWidgetItem*)), SLOT(itemDoubleClicked(QTableWidgetItem*)) ); connect( ui->deliveryDT, SIGNAL(valueChanged(QDateTime)), this, SLOT(checkDate(QDateTime)) ); connect( ui->editNotes, SIGNAL(textChanged()), SLOT(updateNoteLength()) ); //for now, when creating a s.o. the status cannot be modified. It can be when edited. if (newOne) { dateTime = QDateTime::currentDateTime(); ui->deliveryDT->setDateTime(QDateTime::currentDateTime().addDays(1)); } //tip QString path = KStandardDirs::locate("appdata", "styles/"); path = path+"tip.svg"; qtyTip = new MibitTip(this, ui->editQty, path, DesktopIcon("dialog-warning",32) ); path = KStandardDirs::locate("appdata", "styles/")+"rotated_tip.svg"; groupTip = new MibitTip(this, ui->groupView, path, DesktopIcon("dialog-warning",32), tpAbove ); path = KStandardDirs::locate("appdata", "styles/"); path = path+"floating_bottom.svg"; newClientPanel = new MibitFloatPanel(this, path, Top); newClientPanel->setSize(550,250); newClientPanel->addWidget(ui->frameClient); newClientPanel->setMode(pmManual); newClientPanel->setHiddenTotally(true); ui->editClientName->setEmptyMessage(i18n("Enter client name here...")); ui->editClientPhone->setEmptyMessage(i18n("Enter client phone here...")); ui->editClientCell->setEmptyMessage(i18n("Enter client E-mail here...")); connect( ui->btnNewClient, SIGNAL(clicked()), newClientPanel, SLOT(showPanel() )); connect( ui->btnNewClient, SIGNAL(clicked()), this, SLOT(enableCreateClient() )); connect( ui->btnClientCancel, SIGNAL(clicked()), newClientPanel, SLOT(hidePanel())); connect( ui->btnClientAdd, SIGNAL(clicked()), this, SLOT(createClient())); connect( ui->editClientName, SIGNAL(textEdited(const QString &)), this, SLOT(checkValidInfo()) ); connect( ui->editClientAddress, SIGNAL(textChanged()), this, SLOT(checkValidInfo()) ); connect( ui->editClientPhone, SIGNAL(textEdited(const QString &)), this, SLOT(checkValidInfo()) ); connect( ui->editClientCell, SIGNAL(textEdited(const QString &)), this, SLOT(checkValidInfo()) ); setDefaultButton(KDialog::None); ui->btnFilter->setDefault(true); ui->btnFilter->hide(); //hack to dont have a default OK or Cancel button ui->clientsCombo->setFocus(); enableButtonOk(false); } SpecialOrderEditor::~SpecialOrderEditor() { //remove products filter m_model->setFilter(""); m_model->select(); delete ui; } void SpecialOrderEditor::applyFilter(const QString &text) { QRegExp regexp = QRegExp(text); if (!regexp.isValid()) ui->editFilter->setText(""); if (text == "*" || text == "") m_model->setFilter("products.isARawProduct=true and products.isAGroup=false "); else m_model->setFilter(QString("products.isARawProduct=true and products.isAGroup=false and products.name REGEXP '%1'").arg(text)); m_model->select(); } void SpecialOrderEditor::setDb(QSqlDatabase database) { db = database; if (!db.isOpen()) db.open(); populateUsersCombo(); populateClientsCombo(); } // void SpecialOrderEditor::checkMeasureQty() // { // qDebug()<<"Currindex:"<<ui->measuresCombo->currentIndex()<<"curr text:"<<ui->measuresCombo->currentText(); // Azahar *myDb = new Azahar; // myDb->setDatabase(db); // //check qty and combo consistency // int selMeasureId = myDb->getMeasureId(ui->measuresCombo->currentText()); // if (selMeasureId == 1) { // //This is a piece measured item // if ( ui->editQty->text().contains(".") || ui->editQty->text().contains(",") ) { // qDebug()<<"Contains . or , -- its a double!"; // QString reason = i18n("The selected measure is a piece, but the qty is not an integer."); // qtyTip->showTip(reason, 6000); // enableButtonOk(false); // } else checkFieldsState(); // } // } void SpecialOrderEditor::calculateCost() { priceEach = groupInfo.price; paymentEach = priceEach*(.50); double qty = 0; qty = ui->editQty->value(); ui->lblPrice->setText(KGlobal::locale()->formatMoney(priceEach*qty, QString(), 2));//TOTAL! ui->editPayment->setValue(paymentEach*qty); } void SpecialOrderEditor::checkFieldsState() { bool ready = false; if (groupInfo.count > 0 && ui->editPayment->value() > 0) ready = true; enableButtonOk(ready); } void SpecialOrderEditor::slotButtonClicked(int button) { if (button == KDialog::Ok) { QDialog::accept(); } else QDialog::reject(); } void SpecialOrderEditor::setModel(QSqlTableModel *model) { ui->sourcePView->setModel(model); ui->sourcePView->setModelColumn(1); m_model = model; m_modelAssigned = true; //filter to only raw products m_model->setFilter("products.isARawProduct=true AND products.isAGroup=false"); m_model->select(); } void SpecialOrderEditor::addItem() { double dqty = 1; //if not any value, default is ONE QStringList msgP; QStringList msgU; int incTime = 0; Azahar *myDb = new Azahar; myDb->setDatabase(db); if (!ui->editAddQty->text().isEmpty()) { dqty = ui->editAddQty->text().toDouble(); } //get selected items from source view QItemSelectionModel *selectionModel = ui->sourcePView->selectionModel(); QModelIndexList indexList = selectionModel->selectedRows(); // pasar el indice que quiera (0=code, 1=name) foreach(QModelIndex index, indexList) { qulonglong code = index.data().toULongLong(); QString codeStr = index.data().toString(); bool exists = false; ProductInfo pInfo; //get product info from hash or db if (groupInfo.productsList.contains(code)) { pInfo = groupInfo.productsList.take(code); //check measures for the product if (pInfo.units == 1 ) { //by pieces QString tmpStr = ui->editAddQty->text(); if (tmpStr.endsWith(".00")) tmpStr.chop(3); //discard .00's if (tmpStr.endsWith(".0")) tmpStr.chop(2);//discard .00's if (tmpStr.contains(".") || tmpStr.contains(",")) { int tmp = dqty; dqty = tmp; //pass to integer instead of double msgP.append(i18n("<i>%1</i> rounded to %2",pInfo.desc,tmp)); incTime += 1000; } } if (pInfo.stockqty >= pInfo.qtyOnList+dqty) pInfo.qtyOnList += dqty; //increment it else { incTime += 1000; msgU.append(i18n("<i>%1</i> <b>requested %2, on stock %3</b><br>", pInfo.desc,dqty,pInfo.stockqty)); } //if not enough, its not incremented. exists = true; } else { pInfo = myDb->getProductInfo(codeStr); //check measures for the product if (pInfo.units == 1) { //by pieces QString tmpStr = ui->editAddQty->text(); if (tmpStr.endsWith(".00")) tmpStr.chop(3);//discard .00's if (tmpStr.endsWith(".0")) tmpStr.chop(2);//discard .00's if (tmpStr.contains(".") || tmpStr.contains(",")) { int tmp = dqty; dqty = tmp; //pass to integer instead of double msgP.append(i18n("<i>%1</i> rounded to %2",pInfo.desc,tmp)); incTime += 1000; } } pInfo.qtyOnList = 0; if (pInfo.stockqty >= dqty) pInfo.qtyOnList = dqty; else { incTime += 1000; msgU.append(i18n("<i>%1</i> <b>requested %2, on stock %3</b><br>", pInfo.desc,dqty,pInfo.stockqty)); } } // Insert/Update GroupView if (!exists) { //check if it is available. if (pInfo.qtyOnList <= 0 ) { //NO, its not available. continue; qDebug()<<"Continue..."; } // Insert into the groupView int rowCount = ui->groupView->rowCount(); ui->groupView->insertRow(rowCount); ui->groupView->setItem(rowCount, 0, new QTableWidgetItem(QString::number(dqty))); ui->groupView->setItem(rowCount, 1, new QTableWidgetItem(pInfo.desc)); } else { if (pInfo.qtyOnList <= 0 ) { //NO, its not available. continue; qDebug()<<"Continue..."; } //simply update the groupView with the new qty for (int ri=0; ri<ui->groupView->rowCount(); ++ri) { QTableWidgetItem * item = ui->groupView->item(ri, 1); QString name = item->data(Qt::DisplayRole).toString(); if (name == pInfo.desc) { //update QTableWidgetItem *itemQ = ui->groupView->item(ri, 0);//item qty itemQ->setData(Qt::EditRole, QVariant(pInfo.qtyOnList)); continue; } } } // update info of the group groupInfo.count = groupInfo.count+dqty; groupInfo.cost += pInfo.cost*dqty; //pInfo.qtyOnList; groupInfo.price += pInfo.price*dqty; //pInfo.qtyOnList; //NOTE:group price is not affected by any product discount, it takes normal price. // Discounts are taken into consideration after adding to the purchase list, when calculating taxes and price for the SO. bool yes = false; if (pInfo.stockqty >= dqty ) yes = true; groupInfo.isAvailable = (groupInfo.isAvailable && yes ); // Insert product to the group hash groupInfo.productsList.insert(code, pInfo); if (!yes) { //Just warning!... the insert into the view is above... qDebug()<<"Product is not available!"; } } //tip if (!msgP.isEmpty() || !msgU.isEmpty()) { QString msg = "<html>"; //first unavailable items if (!msgU.isEmpty()) msg = msgU.join("\n"); //then invalid qty double/integer if (!msgP.isEmpty()) msg = msg + "\n" + i18n("<b>Product sold by pieces</b>, qty must be an integer value: \n%1",msgP.join("\n")); msg = msg+"</html>"; groupTip->showTip(msg,7000 + incTime); } ui->groupView->resizeRowsToContents(); ui->groupView->resizeColumnsToContents(); ui->groupView->clearSelection(); ui->sourcePView->clearSelection(); //update cost and price on the form, based on group costs //NOTE: Base the cost on components cost calculateCost(); checkFieldsState(); qDebug()<<"There are "<<groupInfo.count<<" items in group. The cost is:"<<groupInfo.cost<<", The price is:"<<groupInfo.price<<" And is available="<<groupInfo.isAvailable; delete myDb; } void SpecialOrderEditor::removeItem() { if (ui->groupView->currentRow() != -1 ){ //get selected item from group view int row = ui->groupView->currentRow(); QTableWidgetItem *item = ui->groupView->item(row, 1); QString name = item->data(Qt::DisplayRole).toString(); Azahar *myDb = new Azahar; myDb->setDatabase(db); //get code from db qulonglong code = myDb->getProductCode(name); ProductInfo pInfo = groupInfo.productsList.take(code); //insert it later... double qty = pInfo.qtyOnList; //from hash | must be the same on groupView if (qty>1) { qty--; item = ui->groupView->item(row, 0); item->setData(Qt::EditRole, QVariant(qty)); pInfo.qtyOnList = qty; groupInfo.productsList.insert(code, pInfo); } else { //delete it from groupView, already removed from hash ui->groupView->removeRow(row); } // update info of the group if (ui->groupView->rowCount() == 0) { groupInfo.count = 0; groupInfo.cost = 0; groupInfo.price = 0; } else { groupInfo.count -= 1; groupInfo.cost -= pInfo.cost; groupInfo.price -= pInfo.price; } bool yes = false; if (pInfo.stockqty >= qty ) yes = true; groupInfo.isAvailable = (groupInfo.isAvailable && yes ); delete myDb; } //there is something selected //update cost and price on the form calculateCost(); checkFieldsState(); qDebug()<<"There are "<<groupInfo.count<<" items in group. The cost is:"<<groupInfo.cost<<", The price is:"<<groupInfo.price<<" And is available="<<groupInfo.isAvailable; } void SpecialOrderEditor::itemDoubleClicked(QTableWidgetItem* item) { int row = item->row(); QTableWidgetItem *itm = ui->groupView->item(row, 1); QString name = itm->data(Qt::DisplayRole).toString(); Azahar *myDb = new Azahar; myDb->setDatabase(db); //get code from db qulonglong code = myDb->getProductCode(name); ProductInfo pInfo = groupInfo.productsList.take(code); //insert it later... double qty = pInfo.qtyOnList+1; //from hash | must be the same on groupView //modify pInfo pInfo.qtyOnList = qty; //increment it one by one //reinsert it to the hash groupInfo.productsList.insert(code, pInfo); //modify groupView itm = ui->groupView->item(row, 0); itm->setData(Qt::EditRole, QVariant(qty)); // update info of the group groupInfo.count += 1; groupInfo.cost += pInfo.cost; groupInfo.price += pInfo.price; bool yes = false; if (pInfo.stockqty > 0 ) //TODO:Falta checar la cantidad que se desea en elgrupo de cada producto yes = true; groupInfo.isAvailable = (groupInfo.isAvailable && yes ); //update cost and price on the form calculateCost(); checkFieldsState(); qDebug()<<"There are "<<groupInfo.count<<" items in group. The cost is:"<<groupInfo.cost<<", The price is:"<<groupInfo.price<<" And is available="<<groupInfo.isAvailable; delete myDb; } QString SpecialOrderEditor::getGroupElementsStr() { QStringList list; foreach(ProductInfo info, groupInfo.productsList) { list.append(QString::number(info.code)+"/"+QString::number(info.qtyOnList)); } return list.join(","); } //this method is not needed because we decided not to use this as a so editor. void SpecialOrderEditor::setGroupElements(QString e) { QStringList list = e.split(","); Azahar *myDb = new Azahar; myDb->setDatabase(db); ProductInfo pInfo; for (int i=0; i<list.count(); ++i) { QStringList tmp = list.at(i).split("/"); if (tmp.count() == 2) { //ok 2 fields qulonglong code = tmp.at(0).toULongLong(); QString codeStr = tmp.at(0); double qty = tmp.at(1).toDouble(); pInfo = myDb->getProductInfo(codeStr); pInfo.qtyOnList = qty; //Insert it to the hash groupInfo.productsList.insert(code, pInfo); //update groupInfo groupInfo.count += qty; groupInfo.cost += pInfo.cost; groupInfo.price += pInfo.price; bool yes = false; if (pInfo.stockqty >= qty ) yes = true; groupInfo.isAvailable = (groupInfo.isAvailable && yes ); //insert it to the groupView int rowCount = ui->groupView->rowCount(); ui->groupView->insertRow(rowCount); ui->groupView->setItem(rowCount, 0, new QTableWidgetItem(QString::number(qty))); ui->groupView->setItem(rowCount, 1, new QTableWidgetItem(pInfo.desc)); } } ui->groupView->resizeRowsToContents(); ui->groupView->resizeColumnsToContents(); calculateCost(); delete myDb; } QString SpecialOrderEditor::getContentNames() { QStringList list; foreach(ProductInfo info, groupInfo.productsList) { QString unitStr; if (info.units == 1 ) unitStr=""; else unitStr = info.unitStr; list.append(" "+QString::number(info.qtyOnList)+" "+unitStr+" "+ info.desc); } //append NOTES for the SO. list.append("\n"+i18n("Notes: %1", getNotes()+" \n")); return list.join("\n"); } void SpecialOrderEditor::checkDate(QDateTime dt) { if (dt.date() </*=*/ QDate::currentDate()) { //allow also deliver for today. Requested by Jnivar. TODO: We could use a config option for this. ui->deliveryDT->setDateTime(QDateTime::currentDateTime()/*.addDays(1)*/); ui->deliveryDT->hide(); ui->lblDateError->setText(i18n("<html><font color=red><b>The delivery date is in the past.</b></font></html>")); ui->lblDateError->show(); QTimer::singleShot(3000,this, SLOT(hideError())); } } void SpecialOrderEditor::hideError() { ui->deliveryDT->show(); ui->lblDateError->setText(""); ui->lblDateError->hide(); } void SpecialOrderEditor::populateUsersCombo() { QSqlQuery query(db); Azahar *myDb = new Azahar; myDb->setDatabase(db); ui->usersCombo->clear(); ui->usersCombo->addItems(myDb->getUsersList()); delete myDb; } void SpecialOrderEditor::populateClientsCombo() { QSqlQuery query(db); Azahar *myDb = new Azahar; myDb->setDatabase(db); ui->clientsCombo->clear(); ui->clientsCombo->addItems(myDb->getClientsList()); delete myDb; } qulonglong SpecialOrderEditor::getClientId() { QSqlQuery query(db); int code=-1; QString currentText = ui->clientsCombo->currentText(); Azahar *myDb = new Azahar; myDb->setDatabase(db); code = myDb->getClientId(currentText); delete myDb; return code; } qulonglong SpecialOrderEditor::getUserId() { QSqlQuery query(db); int code=-1; QString currentText = ui->usersCombo->currentText(); Azahar *myDb = new Azahar; myDb->setDatabase(db); code = myDb->getUserIdFromName(currentText); delete myDb; return code; } QString SpecialOrderEditor::getDescription() { Azahar *myDb = new Azahar; myDb->setDatabase(db); ClientInfo info = myDb->getClientInfo(getClientId()); QStringList phones; phones << info.phone << info.cell; delete myDb; return ui->clientsCombo->currentText() + " [ " +phones.join(", ")+" ]"; } void SpecialOrderEditor::createClient() { //check fields first... bool ready = false; if ( !ui->editClientName->text().isEmpty() && !ui->editClientAddress->toPlainText().isEmpty() ) ready = true; if (ui->editClientPhone->text().isEmpty() && ui->editClientCell->text().isEmpty()) ready = ready && false; //only one can be empty.. else ready = ready && true; if (ready) { ClientInfo info; info.name = ui->editClientName->text(); info.address = ui->editClientAddress->toPlainText(); info.phone = ui->editClientPhone->text(); info.cell = ui->editClientCell->text(); info.points = 0; info.discount= 0; info.since = QDate::currentDate(); info.photo = ""; Azahar *myDb = new Azahar; myDb->setDatabase(db); myDb->insertClient(info); populateClientsCombo(); int index = ui->clientsCombo->findText(info.name,Qt::MatchCaseSensitive); if (index > -1) ui->clientsCombo->setCurrentIndex(index); newClientPanel->hidePanel(); delete myDb; } } void SpecialOrderEditor::checkValidInfo() { bool ready = false; if ( !ui->editClientName->text().isEmpty() && !ui->editClientAddress->toPlainText().isEmpty() ) ready = true; if (ui->editClientPhone->text().isEmpty() && ui->editClientCell->text().isEmpty()) ready = ready && false; //only one can be empty.. else ready = ready && true; ui->btnClientAdd->setEnabled(ready); } void SpecialOrderEditor::enableCreateClient() { ui->btnClientAdd->setEnabled(false); } void SpecialOrderEditor::setUsername(QString username) { int index = ui->usersCombo->findText(username,Qt::MatchCaseSensitive); if (index > -1) ui->usersCombo->setCurrentIndex(index); } ///Use this function after assign the DB! void SpecialOrderEditor::setClientName(QString name) { if (ui->clientsCombo->count() < 1) populateClientsCombo(); //just in case! int index = ui->clientsCombo->findText(name,Qt::MatchCaseSensitive); if (index > -1) ui->clientsCombo->setCurrentIndex(index); else qDebug()<<"CLIENT:"<<name<< "not found."; } //NOTE:this seems to be SLOW! void SpecialOrderEditor::updateNoteLength() { int i = ui->editNotes->toPlainText().length(); ui->lblNoteL->setText(i18n("%1 chars of %2 allowed.", i, 800)); if (i > 800) { ui->editNotes->setText(ui->editNotes->toPlainText().left(800)); ui->editNotes->moveCursor(QTextCursor::End, QTextCursor::MoveAnchor); } } #include "specialordereditor.moc"
22,826
C++
.cpp
580
35.177586
172
0.659309
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
752,805
main.cpp
hiramvillarreal_iotpos/src/main.cpp
/*************************************************************************** * Copyright (C) 2013-2015 by Hiram R. Villarreal * * hiramvillarreal.ap@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "iotpos.h" #include "settings.h" #include <kapplication.h> #include <kaboutdata.h> #include <kcmdlineargs.h> #include <klocale.h> #include <kurl.h> #include <QPixmap> #include <ksplashscreen.h> #include <kstandarddirs.h> #include <QProcess> #include <QStringList> #include <QString> #include <QDir> #include <QDate> static const char description[] = I18N_NOOP("IotPOS, A point of sale for linux"); static const char version[] = "0.9.8.0 | October 04, 2017"; int main(int argc, char **argv) { KAboutData about("iotpos", 0, ki18n("iotpos"), version, ki18n(description), KAboutData::License_GPL, ki18n("(C) 2013-2017 Hiram Ronquillo Villarreal"), KLocalizedString(), 0, "hiramvillarreal.ap@gmail.com"); about.addAuthor( ki18n("Hiram Ronquillo Villarreal"), KLocalizedString(), "hiramvillarreal.ap@gmail.com" ); about.setBugAddress("hiramvillarreal.ap@gmail.com"); KCmdLineArgs::init(argc, argv, &about); about.addCredit(ki18n("Miguel Chavez Gamboa"), ki18n("Code contributor")); about.addCredit(ki18n("Biel Frontera"), ki18n("Code contributor")); about.addCredit(ki18n("Vitali Kari"), ki18n("Code contributor")); about.addCredit(ki18n("Jose Nivar"), ki18n("Many ideas, bug reports and testing")); about.addCredit(ki18n("Roberto Aceves"), ki18n("Many ideas and general help")); about.addCredit(ki18n("Benjamin Burt"), ki18n("Many ideas, Documentation Writer, How-to Videos Creation, and general help and support")); KCmdLineOptions options; //options.add("+[URL]", ki18n( "Document to open" )); KCmdLineArgs::addCmdLineOptions(options); KApplication app; // see if we are starting with session management if (app.isSessionRestored()) RESTORE(iotpos) else { // no session.. just start up normally KCmdLineArgs *args = KCmdLineArgs::parsedArgs(); if (args->count() == 0) { iotpos *widget = new iotpos; widget->show(); } else { int i = 0; for (; i < args->count(); i++) { iotpos *widget = new iotpos; widget->show(); qDebug()<<"iotpos "<<i; } } args->clear(); } return app.exec(); }
3,747
C++
.cpp
79
42.405063
211
0.560274
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
752,806
pricechecker.cpp
hiramvillarreal_iotpos/src/pricechecker.cpp
/************************************************************************** * Copyright © 2013-2015 by Hiram R. Villarreal * * hiramvillarreal.ap@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include <KLocale> #include <QByteArray> #include <QPixmap> #include <kstandarddirs.h> #include "settings.h" #include "pricechecker.h" #include "structs.h" #include "../dataAccess/azahar.h" PriceCheckerUI::PriceCheckerUI( QWidget *parent ) : QFrame( parent ) { setupUi( this ); } PriceChecker::PriceChecker( QWidget *parent ) : KDialog( parent ) { setWindowFlags(Qt::Dialog|Qt::FramelessWindowHint); ui = new PriceCheckerUI( this ); setMainWidget( ui ); setCaption( i18n("Price Checker") ); setButtons( KDialog::NoDefault ); ui->titleTop->setText(i18nc("Price-Checker dialog", "Price")); //FIXME: translation problems!!!!!! ui->titleBottom->setText(i18nc("Price-Checker dialog", "Checker")); //FIXME: translation problems!!!!!! ui->labelPCCode->setText(i18n("&Code:")); ui->labelPCClose->setText(i18n("Press ESC to Close")); ui->labelPClPrice->setText(i18n("Regular price:")); ui->labelPClTotal->setText(i18n("Final price:")); ui->labelPClDiscount->setText(i18n("Discount:")); QString path = KStandardDirs::locate("appdata", "styles/"); QPixmap pix = QPixmap(path + Settings::styleName() + "/priceCheckerBack.png"); resize(517,309); setMask( pix.mask() ); pix = QPixmap(path + Settings::styleName() + "/pricechecker.png"); ui->titleImg->setPixmap(pix); //connect( ui->editCode, SIGNAL(textEdited(const QString &)),this, SLOT(checkIt()) ); //NOTE: There are some issues when having the 'textEdited' signal connected to ckeckIt(), // When you want to use the barcode reader, it sends an enter and then the code is ready to be searched. // Then if you want to read another code to search, the edit line is not cleared. it makes difficult to use it. // So we need to execute the query when the 'enter' event is rised and clean the code input line to let it ready for another search. // With textEdited the code is searched every single number is entered (when not using barcode reader) // causing many database queries to be executed. connect( ui->editCode, SIGNAL(returnPressed()),this, SLOT(checkIt()) ); QRegExp regexpC("[0-9]{1,13}"); QRegExpValidator * validator = new QRegExpValidator(regexpC, this); ui->editCode->setValidator(validator); ui->editCode->setFocus(); myDb = new Azahar; } void PriceChecker::paintEvent(QPaintEvent* event){ QDialog::paintEvent(event); QPainter painter(this); painter.setClipRegion(event->region()); QString path = KStandardDirs::locate("appdata", "styles/"); QPixmap bg = QPixmap(path + Settings::styleName() + "/priceCheckerBack.png"); painter.drawPixmap(QPoint(0,0), bg); } PriceChecker::~PriceChecker() { delete myDb; } void PriceChecker::checkIt() { ProductInfo info = myDb->getProductInfo(ui->editCode->text()); ui->labelPCName->setText(info.desc); ui->labelPCPrice->setText(KGlobal::locale()->formatMoney(info.price)); if (info.validDiscount) ui->labelPCDiscount->setText(KGlobal::locale()->formatMoney(-info.disc)); else ui->labelPCDiscount->setText(KGlobal::locale()->formatMoney(0.0)); double total = info.price; if (info.validDiscount) total = info.price - info.disc; ui->labelPCTotal->setText(KGlobal::locale()->formatMoney(total)); QPixmap pix; pix.loadFromData(info.photo); ui->labelPhoto->setPixmap(pix); //clear the code at the editline. ui->editCode->clear(); } void PriceChecker::setDb(QSqlDatabase database) { myDb->setDatabase(database); } #include "pricechecker.moc"
4,924
C++
.cpp
100
46.99
139
0.63642
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
752,807
iotposview.cpp
hiramvillarreal_iotpos/src/iotposview.cpp
/************************************************************************** * Copyright © 2013-2019 by Hiram R. Villarreal * * hiramvillarreal.ap@gmail.com * * Modified by Daniel A. Cervantes Cabrera * * dcchivela@gmail.com * * Code changes and minor fixes and imporvements by Shane Rees * * pager.pigeon@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "iotposview.h" #include "settings.h" #include "inputdialog.h" #include "productdelegate.h" #include "pricechecker.h" #include "../dataAccess/azahar.h" #include "../printing/print-dev.h" #include "../printing/print-cups.h" #include "ticketpopup.h" #include "misc.h" #include "hash.h" #include "specialordereditor.h" #include "soselector.h" #include "sostatus.h" #include "resume.h" #include "reservations.h" #include "saleqtydelegate.h" #include "dialogclientdata.h" #include "bundlelist.h" #include "../mibitWidgets/mibittip.h" #include "../mibitWidgets/mibitpassworddlg.h" #include "../mibitWidgets/mibitfloatpanel.h" #include "../mibitWidgets/mibitnotifier.h" #include "../iotstock/src/clienteditor.h" #include "BasketPriceCalculationService.h" //StarMicronics printers // #include "printers/sp500.h" #include <QtGui/QPrinter> #include <QtGui/QPrintDialog> #include <QWidget> #include <QStringList> #include <QTimer> #include <QColor> #include <QPixmap> #include <QHeaderView> #include <QTableWidget> #include <QTableWidgetItem> #include <QTextCodec> #include <QRegExp> #include <QRegExpValidator> #include <QValidator> #include <QGridLayout> #include <QDesktopWidget> #include <QPaintEvent> #include <QPainter> #include <QTextDocument> #include <QTextEdit> #include <QPushButton> #include <QDir> #include <QMessageBox> #include <kplotobject.h> #include <kplotwidget.h> #include <kplotaxis.h> #include <kplotpoint.h> #include <klocale.h> #include <kiconloader.h> #include <kstandarddirs.h> #include <kmessagebox.h> #include <kpassivepopup.h> #include <KNotification> #include <QFile> #include <iostream> using namespace std; /* Widgets zone */ /*======================================================================================================================*/ ///NOTE: Testing with KDE 4.2, this TicketPopup dialog was not shown. So it was changed. class BalanceDialog : public QDialog { private: QGridLayout *gridLayout; QTextEdit *editText; QPushButton *buttonClose; public: BalanceDialog(QString str) { setWindowFlags(Qt::Dialog|Qt::FramelessWindowHint); setWindowModality(Qt::ApplicationModal); gridLayout = new QGridLayout(this); editText = new QTextEdit(str); editText->setReadOnly(true); editText->setMinimumSize(QSize(360,260)); gridLayout->addWidget(editText, 0, 0); buttonClose = new QPushButton(this); buttonClose->setText(i18n("Continue")); buttonClose->setDefault(true); buttonClose->setShortcut(Qt::Key_Enter); gridLayout->addWidget(buttonClose, 1,0); connect(buttonClose, SIGNAL(clicked()), this, SLOT(close())); //connect(buttonClose, SIGNAL(clicked()), parent, SLOT(slotDoStartOperation())); } virtual void paint(QPainter *) {} protected: void paintEvent(QPaintEvent *e) { QPainter painter; painter.begin(this); painter.setClipRect(e->rect()); painter.setRenderHint(QPainter::Antialiasing); paint(&painter); painter.restore(); painter.save(); int level = 180; painter.setPen(QPen(QColor(level, level, level), 6)); painter.setBrush(Qt::NoBrush); painter.drawRect(rect()); } }; void iotposView::cancelByExit() { preCancelCurrentTransaction(); Azahar * myDb = new Azahar; myDb->setDatabase(db); myDb->deleteEmptyTransactions(); if (db.isOpen()) { qDebug()<<"Sending close connection to database..."; db.close(); } } iotposView::iotposView() //: QWidget(parent) { //counter = 5; modelsCreated = false; //graphSoldItemsCreated = false; timerCheckDb = new QTimer(this); timerCheckDb->setInterval(3000); // timerUpdateGraphs = new QTimer(this); // timerUpdateGraphs->setInterval(300000); categoriesHash.clear(); // departmentsHash.clear(); //setupSignalConnections(); // QTimer::singleShot(1100, this, SLOT(setupDb())); // QTimer::singleShot(2000, timerCheckDb, SLOT(start())); // QTimer::singleShot(20000, timerUpdateGraphs, SLOT(start())); // QTimer::singleShot(2010, this, SLOT(showWelcomeGraphs())); QTimer::singleShot(2000, this, SLOT(login())); //aquimeme rmTimer = new QTimer(this); //connect(rmTimer, SIGNAL(timeout()), SLOT(reSelectModels()) ); rmTimer->start(1000*60*2); QString mes = (QDate::longMonthName(QDate::currentDate().month())).toUpper(); qDebug()<<"===STARTING IOTPOS AT "<<QDateTime::currentDateTime().toString()<<" ==="; drawerCreated=false; modelsCreated=false; currentBalanceId = 0; availabilityDoesNotMatters = false; doNotAddMoreItems = false; finishingReservation = false; startingReservation = false; reservationPayment = 0; reservationId = 0; QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8")); db = QSqlDatabase::addDatabase("QMYSQL"); //moved here because calling multiple times cause a crash on certain installations (Not kubuntu 8.10). ui_mainview.setupUi(this); dlgLogin = new LoginWindow(i18n("Welcome to IotPOS"), i18n("Enter username and password to start using the system."), LoginWindow::FullScreen); dlgPassword = new LoginWindow(i18n("Authorisation Required"), i18n("Enter administrator password please."), LoginWindow::PasswordOnly); objSales = new KPlotObject( Qt::yellow, KPlotObject::Bars, KPlotObject::Star); ui_mainview.plotSales->addPlotObject( objSales ); ui_mainview.plotSales->axis( KPlotWidget::BottomAxis )->setLabel( i18n("%1", mes) ); ui_mainview.plotSales->axis( KPlotWidget::LeftAxis )->setLabel( i18n("Month Sales (%1)", KGlobal::locale()->currencySymbol()) ); //MibitTips QString path = KStandardDirs::locate("appdata", "styles/"); path = path+"tip.svg"; tipCode = new MibitTip(this, ui_mainview.editItemCode, path, DesktopIcon("dialog-warning",32) ); path = KStandardDirs::locate("appdata", "styles/")+"rotated_tip.svg"; tipAmount = new MibitTip(this, ui_mainview.groupPayment, path, DesktopIcon("dialog-warning",32), tpAbove ); QTimer::singleShot(1000, this, SLOT(setupGridView())); //MibitPasswordDialog path = KStandardDirs::locate("appdata", "styles/") + "dialog.svg"; lockDialog = new MibitPasswordDialog(this, "text", path, DesktopIcon("object-locked",64)); lockDialog->setSize(300,150); lockDialog->setTextColor("Yellow");//Ensure to pass a valid Qt-CSS color name. lockDialog->setShakeTTL(3000); connect(lockDialog, SIGNAL(returnPressed()), this, SLOT(unlockScreen())); //MibitFloatPanel path = KStandardDirs::locate("appdata", "styles/"); path = path+ "tip.svg"; //"panel_top.svg"; //or use the floating_top? currencyPanel = new MibitFloatPanel(ui_mainview.stackedWidget, path, Top); currencyPanel->setSize(200,211); currencyPanel->addWidget(ui_mainview.frameCurrency); currencyPanel->setMode(pmManual); currencyPanel->setHiddenTotally(true); currencyPanel->hide(); //float panel for new discounts. discountPanel = new MibitFloatPanel(ui_mainview.frame, path, Top); discountPanel->setSize(550,250); discountPanel->addWidget(ui_mainview.discountWidget); ui_mainview.rbCoupon->setVisible(false); discountPanel->setMode(pmManual); discountPanel->setHiddenTotally(true); discountPanel->hide(); connect(ui_mainview.rbPercentage, SIGNAL(toggled(bool)), SLOT(changeDiscValidator()) ); connect(ui_mainview.rbMoney, SIGNAL(toggled(bool)), SLOT(changeDiscValidator()) ); connect(ui_mainview.rbPriceChange, SIGNAL(toggled(bool)), SLOT(changeDiscValidator()) ); connect(ui_mainview.rbCoupon, SIGNAL(toggled(bool)), SLOT(changeDiscValidator()) ); oDiscountMoney = 0; //float panel for credits. path = KStandardDirs::locate("appdata", "styles/"); path = path+ "panel_top.svg"; creditPanel = new MibitFloatPanel(ui_mainview.frame, path, Top); creditPanel->setSize(460,300); creditPanel->addWidget(ui_mainview.creditWidget); creditPanel->setMode(pmManual); creditPanel->setHiddenTotally(true); creditPanel->hide(); path = KStandardDirs::locate("appdata", "styles/"); path = path+"tip.svg"; notifierPanel = new MibitNotifier(this,path, DesktopIcon("dialog-warning", 32)); refreshTotalLabel(); QTimer::singleShot(1200, this, SLOT(setupDB())); setAutoFillBackground(true); QTimer::singleShot(1800, this, SLOT(login())); QTimer *timerClock = new QTimer(this); loggedUserRole = roleBasic; //Signals connect(timerClock, SIGNAL(timeout()), SLOT(timerTimeout()) ); connect(ui_mainview.editItemDescSearch, SIGNAL(returnPressed()), this, SLOT(doSearchItemDesc())); //connect(ui_mainview.editItemDescSearch, SIGNAL(textEdited(const QString&)), this, SLOT(doSearchItemDesc())); //WARNING: Above. With many products when searching, it may be too slow and give problems. It is better to have onreturnPressed instead of textEdited signal. connect(ui_mainview.editItemCode, SIGNAL(returnPressed()), this, SLOT(doEmitSignalQueryDb())); connect(this, SIGNAL(signalQueryDb(QString)), this, SLOT(insertItem(QString)) ); //NOTE:Disabling For editing. connect(ui_mainview.tableWidget, SIGNAL(itemDoubleClicked(QTableWidgetItem*)), SLOT(itemDoubleClicked(QTableWidgetItem*)) ); connect(ui_mainview.tableWidget, SIGNAL(itemChanged(QTableWidgetItem*)), this, SLOT(qtyChanged(QTableWidgetItem*))); connect(ui_mainview.tableWidget, SIGNAL(itemDoubleClicked(QTableWidgetItem*)), SLOT(itemDoubleClicked(QTableWidgetItem*)) ); //connect(ui_mainview.tableSearch, SIGNAL(itemDoubleClicked(QTableWidgetItem*)), SLOT(itemSearchDoubleClicked(QTableWidgetItem*)) ); connect(ui_mainview.tableSearch, SIGNAL(itemActivated(QTableWidgetItem*)), SLOT(itemSearchDoubleClicked(QTableWidgetItem*)) ); connect(ui_mainview.tableWidget, SIGNAL(itemClicked(QTableWidgetItem*)), SLOT(displayItemInfo(QTableWidgetItem*))); //connect(ui_mainview.listView, SIGNAL(activated(const QModelIndex &)), SLOT(listViewOnClick(const QModelIndex &))); connect(ui_mainview.listView, SIGNAL(clicked(const QModelIndex &)), SLOT(listViewOnClick(const QModelIndex &))); connect(ui_mainview.listView, SIGNAL(entered(const QModelIndex &)), SLOT(listViewOnMouseMove(const QModelIndex &))); connect(ui_mainview.buttonSearchDone, SIGNAL(clicked()), SLOT(buttonDone()) ); connect(ui_mainview.buttonSearchDone_2, SIGNAL(clicked()), SLOT(buttonDone()) ); connect(ui_mainview.buttonSearchDone_3, SIGNAL(clicked()), SLOT(buttonDone()) ); connect(ui_mainview.checkCard, SIGNAL(toggled(bool)), SLOT(checksChanged()) ); connect(ui_mainview.checkCash, SIGNAL(toggled(bool)), SLOT(checksChanged()) ); connect(ui_mainview.checkOwnCredit, SIGNAL(toggled(bool)), SLOT(checksChanged()) ); connect(ui_mainview.editAmount,SIGNAL(returnPressed()), SLOT(finishCurrentTransaction()) ); connect(ui_mainview.editAmount, SIGNAL(textChanged(const QString &)), SLOT(refreshTotalLabel())); //connect(ui_mainview.editCardNumber, SIGNAL(returnPressed()), SLOT(goSelectCardAuthNumber()) ); //connect(ui_mainview.editCardAuthNumber, SIGNAL(returnPressed()), SLOT(finishCurrentTransaction()) ); connect(ui_mainview.splitter, SIGNAL(splitterMoved(int, int)), SLOT(setUpTable())); connect(ui_mainview.splitterGrid, SIGNAL(splitterMoved(int, int)), SLOT(setUpTable())); connect(ui_mainview.editClient, SIGNAL(returnPressed()), SLOT(filterClient())); connect(ui_mainview.btnChangeSaleDate, SIGNAL(clicked()), SLOT(showChangeDate())); ui_mainview.listView->setStyleSheet("QScrollBar:vertical { width: 25px; }"); ui_mainview.tableWidget->verticalScrollBar()->setStyleSheet("QScrollBar:vertical { width: 25px; }"); ui_mainview.editTicketDatePicker->setDate(QDate::currentDate()); connect(ui_mainview.editTicketDatePicker, SIGNAL(dateChanged(const QDate &)), SLOT(setHistoryFilter()) ); connect(ui_mainview.btnTicketDone, SIGNAL(clicked()), SLOT(btnTicketsDone()) ); connect(ui_mainview.btnTicketPrint, SIGNAL(clicked()), SLOT(printSelTicket()) ); connect(ui_mainview.ticketView, SIGNAL(doubleClicked(const QModelIndex &)), SLOT(itemHIDoubleClicked(const QModelIndex &)) ); connect(ui_mainview.editItemCode, SIGNAL(plusKeyPressed()), this, SLOT(plusPressed())); connect(ui_mainview.btnCurrency, SIGNAL( clicked() ), currencyPanel, SLOT( showPanel() ) ); connect(ui_mainview.btnCurrency, SIGNAL( clicked() ), this, SLOT( getCurrencies() ) ); connect(ui_mainview.btnConvCancel, SIGNAL( clicked() ), currencyPanel, SLOT( hidePanel() ) ); connect(ui_mainview.comboCurrency, SIGNAL(currentIndexChanged(int)), this, SLOT(comboCurrencyOnChange()) ); connect(ui_mainview.editConvQty, SIGNAL(textEdited(const QString&)), SLOT( doCurrencyConversion() ) ); connect(ui_mainview.btnConvOk, SIGNAL(clicked()), SLOT( acceptCurrencyConversion() ) ); connect(ui_mainview.editConvQty, SIGNAL(returnPressed()), SLOT(acceptCurrencyConversion()) ); connect(ui_mainview.btnApplyDiscount, SIGNAL(clicked()), SLOT(applyOccasionalDiscount() ) ); connect(ui_mainview.editDiscount, SIGNAL(returnPressed()), SLOT(applyOccasionalDiscount() ) ); connect(ui_mainview.editDiscount, SIGNAL(textEdited(const QString &)), SLOT(verifyDiscountEntry() ) ); connect(ui_mainview.btnCancelDiscount, SIGNAL(clicked()), discountPanel, SLOT(hidePanel() ) ); connect(ui_mainview.btnPayCredit, SIGNAL(clicked()), SLOT(showCreditPayment())); connect(ui_mainview.editCreditTendered, SIGNAL(textChanged(const QString &)), SLOT(tenderedChanged()) ); connect(ui_mainview.editCreditTendered, SIGNAL(returnPressed()), SLOT(doCreditPayment()) ); connect(ui_mainview.btnCancelCreditPayment, SIGNAL(clicked()), creditPanel, SLOT(hidePanel())); connect(ui_mainview.btnPrintCreditReport, SIGNAL(clicked()), SLOT(printCreditReport())); connect(ui_mainview.editClientIdForCredit, SIGNAL(returnPressed()), SLOT(filterClientForCredit())); connect(ui_mainview.btnAddClient, SIGNAL(clicked()), SLOT(createClient()) ); // connect(timerUpdateGraphs, SIGNAL(timeout()), this, SLOT(updateGraphs())); timerClock->start(1000); drawer = new Gaveta(); drawer->setPrinterDevice(Settings::printerDevice()); //NOTE: setPrinterDevice: what about CUPS printers recently added support for? drawerCreated = true; operationStarted = false; productsHash.clear(); specialOrders.clear(); clientsHash.clear(); bundlesHash = new BundleList(); //remember to delete it. //ui_mainview.lblClientPhoto->hide(); //ui_mainview.labelInsertCodeMsg->hide(); transDateTime = QDateTime::currentDateTime(); ui_mainview.editTransactionDate->setDateTime(transDateTime); ui_mainview.groupSaleDate->hide(); // ui_mainview.plotSales->update(); ui_mainview.editItemCode->setEmptyMessage(i18n("Enter description, code, qty*code <Enter> or <+> Keys to go pay. <->Price<Enter> to search by price.")); ui_mainview.editItemCode->setToolTip(i18n("Enter description, code, qty*code <Enter> or <+> Keys to go pay. <->Price<Enter> to search by price.")); ui_mainview.editCreditTendered->setEmptyMessage(i18n("Enter an amount.")); clearUsedWidgets(); loadIcons(); setUpInputs(); QTimer::singleShot(500, this, SLOT(setUpTable())); //ui_mainview.groupWidgets->setCurrentIndex(pageMain); ui_mainview.mainPanel->setCurrentIndex(pageMain); // point the public ui pointers frameLeft = ui_mainview.frameLeft; frame = ui_mainview.frame; //hide or show the subtotal labels if (!Settings::addTax()) { ui_mainview.lblSubtotalPre->hide(); ui_mainview.lblSubtotal->hide(); qDebug()<<"hiding subtotal label, not using addTax option."; } //excluded list for the random messages on tickets. rmExcluded.clear(); //NOTE: this list is populated by the Azahar::getRandomMessage() method. //calculate the season... Here are different ways, by months -the easier- or by groups of months. QDate today = QDate::currentDate(); rmSeason = today.month(); // switch (today.month()) { // //-- Christmas time // case 12: // case 1: // case 2: // //-- // case 3: // case 4: // case 5: // case 6: // case 7: // case 8: // case 9: // case 10: // case 11: // } ui_mainview.editItemCode->setFocus(); ui_mainview.rbFilterByDesc->setChecked(true); setupGridView(); ui_mainview.labelTotalDiscountpre->hide(); ui_mainview.labelTotalDiscount->hide(); int x = (QApplication::desktop()->width()); if (x < 600) ui_mainview.frameLeft->hide(); setupGraphs(); } // UI and Database -- GRAPHS. void iotposView::updateGraphs() { if (!db.isOpen()) setupDB(); if (loggedUserRole == roleAdmin) { qDebug() << " update Graphs " << endl; //if (!db.isOpen());{ } if (db.isOpen()) { if (!graphSoldItemsCreated ) setupGraphs(); else{ // cout << " ----------------->>>>>> DB is Open " << endl; Azahar *myDb = new Azahar(this); myDb->setDatabase(db); ///First we need to get data for the plots QList<TransactionInfo> monthTrans = myDb->getMonthTransactionsForPie(); // ProfitRange rangeP = myDb->getMonthProfitRange(); ProfitRange rangeS = myDb->getMonthSalesRange(); //qDebug()<<"** [Ranges] Profit:"<<rangeP.min<<","<<rangeP.max<<" Sales:"<<rangeS.min<<","<<rangeS.max; TransactionInfo info; ///plots objSales->clearPoints(); int hoy=0; hoy = QDate::currentDate().day(); ui_mainview.plotSales->setLimits(0, hoy+1, rangeS.min-rangeS.min*.10, rangeS.max+rangeS.max*.10); int day=0; double AccSales=0.0; double AccProfit=0.0; objSales->addPoint(0,0, "0"); if (!monthTrans.isEmpty()) { // cout <<"-----------------> monthTrans is not empty " << endl; TransactionInfo inf; inf.date = monthTrans.last().date.addDays(1); inf.amount = 0; inf.utility = 0; monthTrans.append(inf); } //END Fix old issue. // int day=0; double AccSales=0.0; double AccProfit=0.0; for (int i = 0; i < monthTrans.size(); ++i) { info = monthTrans.at(i); ///we got one result per day (sum) //insert the day,profit to the plot AccSales = info.amount; AccProfit = info.utility; day = info.date.day(); objSales->addPoint(day,AccSales, QString::number(AccSales)); //objProfit->addPoint(day,AccProfit, QString::number(AccProfit)); qDebug()<<"ITERATING MONTH TRANSACTIONS | "<<day<<", sales:"<<info.amount<<" profit:"<<info.utility<<" AccSales:"<<AccSales<<" AccProfit:"<<AccProfit; //ui_mainview.plotSales->update(); } //for each eleement // ui_mainview.plotSales->update(); delete myDb; } } } } void iotposView::setupGraphs() { if (!db.isOpen()) setupDB(); if (db.isOpen()) objSales->setShowBars(true); objSales->setShowPoints(true); objSales->setShowLines(true); objSales->setLinePen( QPen( Qt::blue, 1.5, Qt::DashDotLine ) ); objSales->setBarBrush( QBrush( Qt::lightGray, Qt::Dense6Pattern ) ); objSales->setBarPen(QPen(Qt::lightGray)); objSales->setPointStyle(KPlotObject::Star); graphSoldItemsCreated = true; } void iotposView::qtyChanged(QTableWidgetItem *item) { //NOTE: This method is executed only when the data is changed. If the delegate does not allow the change, then this is not executed (signal not emitted). ///NOTE: Allow price change this way too?. It is more difficult than qty change, implies permissions. /// The spinbox only support integers. We need a config option to turn ON/OFF this feature. if (item && item->column() == colQty) { //item == ui_mainview.tableWidget ->currentItem() && //TODO:Create and assign a delegate to handle limits on the spinbox. //get item code int row = item->row(); double newQty = item->data(Qt::DisplayRole).toDouble(); QTableWidgetItem *i2Modify = ui_mainview.tableWidget->item(row, colCode); qulonglong code = i2Modify->data(Qt::DisplayRole).toULongLong(); //is it an SO or a product? if ( !productsHash.contains(code) ) { qDebug()<<"Product not in the hash. SpecialOrders are not supported yet."; } else { //ok so now check qtys to see if they are available at stock. ProductInfo info = productsHash.take(code); double stockqty = info.stockqty; QStringList itemsNotAvailable; bool available = true; double old_qty = info.qtyOnList;//To reject the new qty if not available. qDebug()<<"Old item on list:"<<old_qty; if (info.isAGroup) { Azahar *myDb = new Azahar; myDb->setDatabase(db); QStringList lelem = info.groupElementsStr.split(","); foreach(QString ea, lelem) { qulonglong c = ea.section('/',0,0).toULongLong(); double qq = ea.section('/',1,1).toDouble(); ProductInfo pi = myDb->getProductInfo(QString::number(c)); QString unitStr; bool yes = false; double onList = getTotalQtyOnList(pi); // item itself and contained in any gruped product. // q : item qty to add == newQty here // qq : item qty on current grouped element to add // qq*q : total items to add for this product. // onList: items of the same product already on the shopping list. if (pi.stockqty >= ((qq*newQty)+onList) ) yes = true; available = (available && yes ); if (!yes) { itemsNotAvailable << i18n("%1 has %2 %3 but requested %4 + %5",pi.desc,pi.stockqty,unitStr,qq*newQty,onList); } qDebug()<<pi.desc<<" qtyonstock:"<<pi.stockqty<<" needed qty (onlist and new):"<<QString::number((qq*newQty)+onList); } delete myDb; } else { double onList = getTotalQtyOnList(info); // item itself and contained in any gruped product. if (stockqty >= newQty+onList) available = true; else available = false; qDebug()<<info.desc<<" qtyonstock:"<<info.stockqty<<" needed qty (onlist and new):"<<QString::number(newQty+onList); } if (!available) { QString msg; double onList = getTotalQtyOnList(info); // item itself and contained in any gruped product. //remove the inserted qty by the user (restore old_qty) item->setData(Qt::EditRole, QVariant(old_qty)); qDebug()<<"Se restablecio la cantidad original de:"<<old_qty<<". Se ignora la cantidad requerida:"<<newQty; if (!itemsNotAvailable.isEmpty()) msg = i18n("<html><font color=red><b>The group/pack is not available because:<br>%1</b></font></html>", itemsNotAvailable.join("<br>")); else msg = i18n("<html><font color=red><b>There are only %1 articles of your choice at stock.<br> You requested %2</b></font></html>", info.stockqty,newQty+onList); if (ui_mainview.mainPanel->currentIndex() == pageMain) { ui_mainview.editItemCode->clearFocus(); tipCode->showTip(msg, 6000); } if (ui_mainview.mainPanel->currentIndex() == pageSearch) { ui_mainview.labelSearchMsg->setText(msg); ui_mainview.labelSearchMsg->show(); QTimer::singleShot(3000, this, SLOT(clearLabelSearchMsg()) ); } } else { //Available, continue... info.qtyOnList = newQty; productsHash.insert(info.code, info); updateItem(info); refreshTotalLabel(); ui_mainview.editItemCode->setFocus(); setupGridView(); qDebug()<<"\n\nCurrent Item == item: "<<code<<" NEW QTY:"<<newQty<<"\n\n"; } } } } void iotposView::showChangeDate() { ui_mainview.groupSaleDate->show(); } void iotposView::setupGridView() { if (Settings::showGrid()) emit signalShowProdGrid(); else showProductsGrid(false); } void iotposView::loadIcons() { ui_mainview.labelImageSearch->setPixmap(DesktopIcon("edit-find", 64)); QString logoBottomFile = KStandardDirs::locate("appdata", "images/logo_bottom.png"); ui_mainview.labelBanner->setPixmap(QPixmap(logoBottomFile)); ui_mainview.labelBanner->setAlignment(Qt::AlignCenter); } void iotposView::setUpTable() { QSize tableSize = ui_mainview.tableWidget->size(); int portion = tableSize.width()/6; ui_mainview.tableWidget->horizontalHeader()->setFixedHeight(24); int x = (QApplication::desktop()->width()); if (x < 600){ ui_mainview.tableWidget->horizontalHeader()->setResizeMode(QHeaderView::Interactive); ui_mainview.tableWidget->horizontalHeader()->resizeSection(colQty, (portion/1.5)); //QTY ui_mainview.tableWidget->horizontalHeader()->resizeSection(colUnits, (portion/3)+20);//UNITS ui_mainview.tableWidget->horizontalHeader()->resizeSection(colDesc, (portion*2.75)); //DESCRIPTION ui_mainview.tableWidget->horizontalHeader()->resizeSection(colPrice, (portion)-10); //PRICE ui_mainview.tableWidget->horizontalHeader()->resizeSection(colDue, (portion)-10); //DUE ui_mainview.tableWidget->hideColumn(0); ui_mainview.tableWidget->hideColumn(5); } else{ ui_mainview.tableWidget->horizontalHeader()->setResizeMode(QHeaderView::Interactive); ui_mainview.tableWidget->horizontalHeader()->resizeSection(colCode, portion-20); //BAR CODE ui_mainview.tableWidget->horizontalHeader()->resizeSection(colQty, (portion/3)+10); //QTY ui_mainview.tableWidget->horizontalHeader()->resizeSection(colUnits, (portion/3)+10);//UNITS ui_mainview.tableWidget->horizontalHeader()->resizeSection(colDesc, (portion*2.7)); //DESCRIPTION ui_mainview.tableWidget->horizontalHeader()->resizeSection(colPrice, (portion/2)); //PRICE ui_mainview.tableWidget->horizontalHeader()->resizeSection(colDisc, (portion/2)+10); //Discount ui_mainview.tableWidget->horizontalHeader()->resizeSection(colDue, (portion/2)); //DUE //resizeSearchTable(); } } void iotposView::resizeSearchTable() { QSize tableSize = ui_mainview.tableSearch->size(); int portion = tableSize.width()/7; ui_mainview.tableSearch->horizontalHeader()->setResizeMode(QHeaderView::Interactive); ui_mainview.tableSearch->horizontalHeader()->resizeSection(0, portion*1); //QTY ui_mainview.tableSearch->horizontalHeader()->resizeSection(1, portion*2); //UNIT ui_mainview.tableSearch->horizontalHeader()->resizeSection(2, portion*3); //DESCRIPTION ui_mainview.tableSearch->horizontalHeader()->resizeSection(3, portion*4); //PRICE ui_mainview.tableSearch->horizontalHeader()->resizeSection(4, portion*5);//TOTAL ui_mainview.tableSearch->horizontalHeader()->resizeSection(5, portion*6); //DISCOUNT ui_mainview.tableSearch->horizontalHeader()->resizeSection(6, portion*7); //CODE } void iotposView::resizeSearchTableSmall() { QSize tableSize = ui_mainview.tableSearch->size(); int portion = tableSize.width()/5; ui_mainview.tableSearch->horizontalHeader()->setResizeMode(QHeaderView::Interactive); ui_mainview.tableSearch->horizontalHeader()->resizeSection(0, portion*1); //QTY ui_mainview.tableSearch->horizontalHeader()->resizeSection(1, portion*2); //UNIT ui_mainview.tableSearch->horizontalHeader()->resizeSection(2, portion*3); //DESCRIPTION ui_mainview.tableSearch->horizontalHeader()->resizeSection(3, portion*4); //PRICE ui_mainview.tableSearch->horizontalHeader()->resizeSection(4, portion*5);//TOTAL } void iotposView::setUpInputs() { //TODO: Tratar de poner un filtro con lugares llenos de ceros, e ir insertando los numeros. //For amount received. QRegExp regexpA("[0-9]*[//.]{0,1}[0-9]{0,5}"); //QRegExp regexpA("[0-9]*[//.]{0,1}[0-9][0-9]*"); //Cualquier numero flotante (0.1, 100, 0, .10, 100.0, 12.23) QRegExpValidator * validatorFloat = new QRegExpValidator(regexpA,this); ui_mainview.editAmount->setValidator(validatorFloat); //Item code (to insert) // //QRegExp regexpC("[0-9]+[0-9]*[//.]{0,1}[0-9]{0,2}[//*]{0,1}[0-9]*[A-Za-z_0-9\\\\/\\-]{0,30}"); // Instead of {0,13} fro EAN13, open for up to 30 chars. QRegExp regexpC("[0-9]*[//.]{0,1}[0-9]{0,5}[//*]{0,1}[0-9]*[A-Za-z_0-9\\s\\/\\-]{0,30}"); // Instead of {0,13} fro EAN13, open for up to 30 chars. //NOTE: We remove the xX from the regexp for use as the separator between qtys and code. Only * can be used now, for Alphacode support QRegExpValidator * validatorEAN13 = new QRegExpValidator(regexpC, this); ui_mainview.editItemCode->setValidator(validatorEAN13); QRegExp regexpAN("[A-Za-z_0-9\\\\/\\-]+");//any letter, number, both slashes, dash and lower dash. QRegExpValidator *regexpAlpha = new QRegExpValidator(regexpAN, this); //ui_mainview.editCardAuthNumber->setValidator(regexpAlpha); //QRegExp regexpCC("[0-9]{1,13}"); //We need to support also names. So we need to remove this validator. Just text QRegExp regexpAN2("[A-Za-z_0-9\\s\\\\/\\-]+");//any letter, number, both slashes, dash and lower dash. and any space QRegExpValidator *regexpAlpha2 = new QRegExpValidator(regexpAN2, this); ui_mainview.editClientIdForCredit->setValidator(regexpAlpha2); ui_mainview.editClient->setValidator(regexpAlpha2); //ui_mainview.editAmount->setInputMask("000,000.00"); //filter for new discount edit line. at the begining, it is by percentage discount the default. valPercentage = new QDoubleValidator(0.001, 99.000, 3, this); valMoney = new QDoubleValidator(0.001, 9999999, 3, this); ui_mainview.editDiscount->setValidator(valPercentage); ui_mainview.editDiscount->setAutoClearError(true); //NOTE: DoubleValidator does not filter characters at the input (as the RegExpValidator does). It just will NOT ACCEPT the value. ui_mainview.editCreditTendered->setValidator(validatorFloat); ui_mainview.creditPaymentWidget->hide(); QDoubleValidator *dVal = new QDoubleValidator(0.001, 18440000000000000000.0, 4, this); ui_mainview.editCreditTendered->setValidator(dVal); } void iotposView::changeDiscValidator() { if (ui_mainview.rbPercentage->isChecked()) { ui_mainview.editDiscount->setValidator(valPercentage); } else if (ui_mainview.rbMoney->isChecked()) { ui_mainview.editDiscount->setValidator(valMoney); } else if (ui_mainview.rbPriceChange->isChecked()) { ui_mainview.editDiscount->setValidator(valMoney); } else { //a string... for coupons STILL NOT IMPLEMENTED! } ui_mainview.editDiscount->clear(); ui_mainview.editDiscount->setFocus(); } void iotposView::verifyDiscountEntry() { if ( !ui_mainview.editDiscount->hasAcceptableInput() ) { ui_mainview.editDiscount->setError(i18n("Invalid input")); } else { ui_mainview.editDiscount->clearError(); } } void iotposView::timerTimeout() { emit signalUpdateClock(); } void::iotposView::clearLabelSearchMsg() { ui_mainview.labelSearchMsg->clear(); } void iotposView::setTheSplitterSizes(QList<int> s) { ui_mainview.splitter->setSizes(s); } QList<int> iotposView::getTheSplitterSizes() { return ui_mainview.splitter->sizes(); } void iotposView::setTheGridSplitterSizes(QList<int> s) { ui_mainview.splitterGrid->setSizes(s); } QList<int> iotposView::getTheGridSplitterSizes() { return ui_mainview.splitterGrid->sizes(); } //This ensures that when not connected to mysql, the user can configure the db settings and then trying to connect //with the new settings... void iotposView::settingsChanged() { //Total label (and currency label) refreshTotalLabel(); ///This is a temporal workaround for the crash. I think is due to a kde bug. It does not crashes with kde 4.1.4 on kubuntu //Reconnect to db.. if (db.isOpen()) db.close(); qDebug()<<"-Config Changed- reconnecting to database.."; db.setHostName(Settings::editDBServer()); db.setDatabaseName(Settings::editDBName()); db.setUserName(Settings::editDBUsername()); db.setPassword(Settings::editDBPassword()); connectToDb(); setupModel(); setupHistoryTicketsModel(); currentBalanceId = 0; insertBalance(); //this updates the currentBalanceId startAgain(); syncSettingsOnDb(); } void iotposView::syncSettingsOnDb() { //save new settings on db -to avoid double settings on iotpos and iotstock- Azahar *myDb = new Azahar; myDb->setDatabase(db); if (!Settings::storeLogo().isEmpty()) { QPixmap p = QPixmap( Settings::storeLogo() ); QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); myDb->setConfigStoreLogo(Misc::pixmap2ByteArray(new QPixmap(p), p.size().width(),p.size().height())); QApplication::restoreOverrideCursor(); } myDb->setConfigStoreName(Settings::editStoreName()); myDb->setConfigStoreAddress(Settings::storeAddress()); myDb->setConfigStorePhone(Settings::storePhone()); myDb->setConfigSmallPrint(!Settings::bigReceipt()); myDb->setConfigUseCUPS(!Settings::smallTicketDotMatrix()); myDb->setConfigLogoOnTop(Settings::chLogoOnTop()); myDb->setConfigTaxIsIncludedInPrice(!Settings::addTax());//NOTE: the AddTax means the tax is NOT included in price, thats why this is negated. delete myDb; } void iotposView::settingsChangedOnInitConfig() { qDebug()<<"==> Initial Config Changed- connecting to database and calling login..."; //the db = QSqlDatabase... thing is causing a crash. //QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8")); //db = QSqlDatabase::addDatabase("QMYSQL"); db.setHostName(Settings::editDBServer()); db.setDatabaseName(Settings::editDBName()); db.setUserName(Settings::editDBUsername()); db.setPassword(Settings::editDBPassword()); ///This is also affected by the weird crash. connectToDb(); setupModel(); setupHistoryTicketsModel(); currentBalanceId = 0; insertBalance(); //this updates the currentBalanceId startAgain(); emit signalDisableStartOperationAction(); login(); } void iotposView::showEnterCodeWidget() { //ui_mainview.groupWidgets->setCurrentIndex(pageMain); ui_mainview.stackedWidget_3->setCurrentIndex(1); ui_mainview.listView->scrollToTop(); ui_mainview.mainPanel->setCurrentIndex(0); // back to welcome widget // BFB. Toggle editItemCode and editFilterByDesc. if (!ui_mainview.editItemCode->hasFocus()){ ui_mainview.editItemCode->setFocus(); } setupGridView(); //ui_mainview.lblSubtotalPre->show(); //ui_mainview.lblSubtotal->show(); //ui_mainview.labelChangepre->hide(); //ui_mainview.labelChange->hide(); setUpTable(); } void iotposView::showSearchItemWidget() { ui_mainview.mainPanel->setCurrentIndex(pageSearch); // searchItem ui_mainview.editItemDescSearch->setFocus(); setUpTable(); } void iotposView::buttonDone() { ui_mainview.tableSearch->setRowCount(0); ui_mainview.labelSearchMsg->setText(""); ui_mainview.editItemDescSearch->setText(""); ui_mainview.editItemCode->setCursorPosition(0); ui_mainview.mainPanel->setCurrentIndex(0); // back to welcome widget setupGridView(); ui_mainview.stackedWidget_3->setCurrentIndex(1); ui_mainview.listView->scrollToTop(); ui_mainview.editItemCode->setFocus(); //ui_mainview.lblSubtotalPre->show(); //ui_mainview.lblSubtotal->show(); //ui_mainview.labelChangepre->hide(); //ui_mainview.labelChange->hide(); } void iotposView::checksChanged() { bool readOnly = ui_mainview.checkOwnCredit->isChecked() || ui_mainview.checkCard->isChecked(); ui_mainview.editAmount->setReadOnly(readOnly); if (ui_mainview.checkCash->isChecked()) { ui_mainview.stackedWidget->setCurrentIndex(0); ui_mainview.editAmount->setFocus(); ui_mainview.editAmount->setSelection(0,ui_mainview.editAmount->text().length()); }//cash else if (ui_mainview.checkCard->isChecked()) //Card, need editCardkNumber... { ui_mainview.editAmount->setText(QString::number(totalSum)); ui_mainview.editAmount->setFocus(); } else { //own credit. Do not allow change the amount. ui_mainview.stackedWidget->setCurrentIndex(0); ui_mainview.editAmount->setText(QString::number(totalSum)); ui_mainview.editAmount->setFocus(); } refreshTotalLabel(); } void iotposView::clearUsedWidgets() { ui_mainview.editAmount->setText(""); //ui_mainview.editCardNumber->setText(""); //ui_mainview.editCardAuthNumber->setText("-"); ui_mainview.tableWidget->clearContents(); ui_mainview.tableWidget->setRowCount(0); totalSum = 0.0; buyPoints = 0; ui_mainview.labelDetailTax1->setText(""); ui_mainview.labelDetailTax2->setText(""); ui_mainview.labelDetailUnits->setText(""); ui_mainview.labelDetailDesc->setText(i18n("No product selected")); ui_mainview.labelDetailPrice->setText(""); ui_mainview.labelDetailDiscount->setText(""); ui_mainview.labelDetailTotalTaxes->setText(""); ui_mainview.labelDetailPhoto->clear(); ui_mainview.labelDetailPoints->clear(); //enable clients combo box... ui_mainview.groupClient->setEnabled(true); ui_mainview.editClient->setText(""); } void iotposView::askForIdToCancel() { bool continuar=false; if (Settings::lowSecurityMode()) {//qDebug()<<"LOW security mode"; continuar=true; } else if (Settings::requiereDelAuth()) {// qDebug()<<"NO LOW security mode, but AUTH REQUIRED!"; dlgPassword->show(); dlgPassword->hide(); dlgPassword->clearLines(); continuar = dlgPassword->exec(); } else {// qDebug()<<"NO LOW security mode, NO AUTH REQUIRED..."; continuar=true; } if (continuar) { //show input dialog to get ticket number bool ok=false; qulonglong id = 0; InputDialog *dlg = new InputDialog(this, true, dialogTicket, i18n("Enter the ticket number to cancel")); if (dlg->exec()) { id = dlg->iValue; ok = true; } delete dlg; if (ok) { // NOTE : cancelTransaction(id); //Mark as cancelled in database.. is this transaction //done in the current operation, or a day ago, a month ago, 10 hours ago? //Allow cancelation of same day of sell, or older ones too? }//ok=true } //continuar } ///NOTE: Not implemented yet void iotposView::askForTicketToReturnProduct() { bool continuar=false; if (Settings::lowSecurityMode()) {//qDebug()<<"LOW security mode"; continuar=true; } else if (Settings::requiereDelAuth()) {// qDebug()<<"NO LOW security mode, but AUTH REQUIRED!"; dlgPassword->show(); dlgPassword->hide(); dlgPassword->clearLines(); continuar = dlgPassword->exec(); } else {// qDebug()<<"NO LOW security mode, NO AUTH REQUIRED..."; continuar=true; } if (continuar) { //show input dialog to get ticket number bool ok=false; InputDialog *dlg = new InputDialog(this, true, dialogTicket, i18n("Enter the ticket number")); if (dlg->exec()) { ok = true; } delete dlg; if (ok) { // show dialog to select which items to return. }//ok=true } //continuar } void iotposView::focusPayInput() { ui_mainview.groupWidgets->setCurrentIndex(pageMain); ui_mainview.mainPanel->setCurrentIndex(0); // back to welcome widget ui_mainview.editAmount->setSelection(0, ui_mainview.editAmount->text().length()); ui_mainview.editAmount->setFocus(); ui_mainview.editAmount->setText(QString::number(totalSum)); ui_mainview.stackedWidget_3->setCurrentIndex(2); //ui_mainview.lblSubtotalPre->hide(); ui_mainview.checkCash->setChecked(true); //ui_mainview.lblSubtotal->hide(); //ui_mainview.labelChangepre->show(); //ui_mainview.labelChange->show(); hideProductsGrid(); ui_mainview.labelDetailTax1->setText(""); ui_mainview.labelDetailTax2->setText(""); ui_mainview.labelDetailUnits->setText(""); ui_mainview.labelDetailDesc->setText(i18n("No product selected")); ui_mainview.labelDetailPrice->setText(""); ui_mainview.labelDetailDiscount->setText(""); ui_mainview.labelDetailTotalTaxes->setText(""); ui_mainview.labelDetailPhoto->clear(); ui_mainview.labelDetailPoints->clear(); ui_mainview.editAmount->selectAll(); } //This method sends the focus to the amount to be paid only when the code input is empty. void iotposView::plusPressed() { if ( !ui_mainview.editItemCode->text().isEmpty() ) doEmitSignalQueryDb(); else focusPayInput(); } void iotposView::goSelectCardAuthNumber() { //ui_mainview.editCardAuthNumber->setFocus(); } void iotposView::getCurrencies() { Azahar *myDb = new Azahar(); myDb->setDatabase(db); //get currencies from database QList<CurrencyInfo> currencyList = myDb->getCurrencyList(); //load currencies to combobox if ( ui_mainview.comboCurrency->count() > 0 ) ui_mainview.comboCurrency->clear(); foreach( CurrencyInfo info, currencyList ) { ui_mainview.comboCurrency->addItem( info.name ); } //select first one and set the factor to the edit. if ( !currencyList.isEmpty() ) { CurrencyInfo info = currencyList.first(); ui_mainview.editConvFactor->setText( QString::number(info.factor) ); } ui_mainview.editConvQty->setFocus(); delete myDb; } void iotposView::comboCurrencyOnChange() { Azahar *myDb = new Azahar(); myDb->setDatabase(db); CurrencyInfo info = myDb->getCurrency( ui_mainview.comboCurrency->currentText() ); ui_mainview.editConvFactor->setText( QString::number( info.factor ) ); doCurrencyConversion(); ui_mainview.editConvQty->setFocus(); delete myDb; } void iotposView::doCurrencyConversion() { if ( !ui_mainview.editConvQty->text().isEmpty() && !ui_mainview.editConvFactor->text().isEmpty() ) { double qty = 0; double factor = 0; double result = 0; qty = ui_mainview.editConvQty->text().toDouble(); factor = ui_mainview.editConvFactor->text().toDouble(); result = qty * factor; ui_mainview.editConvResult->setText( QString::number( result ) ); qDebug()<<"CURRENCY CONVERSION -- qty:"<<qty<<" factor:"<<factor<<" RESULT:"<<result<<" Result converted to string:"<<QString::number(result); } } void iotposView::acceptCurrencyConversion() { ui_mainview.editAmount->setText( ui_mainview.editConvResult->text() ); currencyPanel->hidePanel(); ui_mainview.editAmount->setFocus(); } void iotposView::populateCardTypes() { Azahar *myDb = new Azahar(); myDb->setDatabase(db); //get currencies from database QStringList cardTypes = myDb->getCardTypes(); //load currencies to combobox if ( ui_mainview.comboCardType->count() > 0 ) ui_mainview.comboCardType->clear(); foreach( QString type, cardTypes ) { ui_mainview.comboCardType->addItem( type ); } delete myDb; } iotposView::~iotposView() { drawerCreated=false; delete drawer; } /* Users zone */ /*=====================================================================================================================*/ QString iotposView::getLoggedUser() { return loggedUser; } QString iotposView::getLoggedUserName(QString id) { QString uname = ""; Azahar *myDb = new Azahar; myDb->setDatabase(db); uname = myDb->getUserName(id); delete myDb; return uname; } int iotposView::getUserRole(qulonglong id) { int role = 0; Azahar *myDb = new Azahar; myDb->setDatabase(db); role = myDb->getUserRole(id); delete myDb; return role; } qulonglong iotposView::getLoggedUserId(QString uname) { unsigned int iD=0; Azahar *myDb = new Azahar; myDb->setDatabase(db); iD = myDb->getUserId(uname); delete myDb; return iD; } void iotposView::login() { qDebug()<<"Login.. emiting disable startop action"; emit signalDisableStartOperationAction(); corteDeCaja(); //Make a corteDeCaja "BALANCE" loggedUser = ""; loggedUserName =""; loggedUserRole = roleBasic; //qDebug()<<"In Cash:"<<drawer->getAvailableInCash()<<"Transactions:"<<drawer->getTransactionsCount(); drawer->reset(); emit signalNoLoggedUser(); dlgLogin->clearLines(); if (!db.isOpen()) { qDebug()<<"(login): Calling connectToDb()..."; connectToDb(); } if (!db.isOpen()) { qDebug()<<"(login): Still unable to open connection to database...."; QString msg = i18n("Could not connect to database, please press 'login' button again to raise a database configuration."); KPassivePopup::message( i18n("Error:"),msg, DesktopIcon("dialog-error", 48), this ); } else { if ( dlgLogin->exec() ) { loggedUser = dlgLogin->username(); loggedUserName = getLoggedUserName(loggedUser); loggedUserId = getLoggedUserId(loggedUser); loggedUserRole = getUserRole(loggedUserId); emit signalLoggedUser(); //Now check roles instead of names if (loggedUserRole == roleAdmin) { emit signalAdminLoggedOn(); ui_mainview.labelBanner->setVisible(true); // updateGraphs(); //if (!canStartSelling()) startOperation(); } else { emit signalAdminLoggedOff(); if (loggedUserRole == roleSupervisor) { ui_mainview.labelBanner->setVisible(true); emit signalSupervisorLoggedOn();} else { emit signalEnableStartOperationAction(); ui_mainview.labelBanner->setVisible(true); //slotDoStartOperation(); } } } else { loggedUser =""; loggedUserName = ""; loggedUserId = 0; loggedUserRole = roleBasic; emit signalNoLoggedUser(); if (dlgLogin->wantToQuit()) qApp->quit(); } } } bool iotposView::validAdminUser() { bool result = false; if (Settings::lowSecurityMode()) result = true; else { dlgPassword->show(); dlgPassword->hide(); dlgPassword->clearLines(); if (dlgPassword->exec()) result = true; } return result; } /* Item things: shopping list, search, insert, delete, calculate total */ /*--------------------------------------------------------------------*/ void iotposView::doSearchItemDesc() { //clear last search ui_mainview.tableSearch->clearContents(); ui_mainview.tableSearch->setRowCount(0); //Search QString desc = ui_mainview.editItemDescSearch->text(); QRegExp regexp = QRegExp(desc); if (!regexp.isValid() || desc.isEmpty()) desc = "*"; if (!db.isOpen()) db.open(); Azahar *myDb = new Azahar; myDb->setDatabase(db); QList<qulonglong> pList = myDb->getProductsCode(desc); //busca con regexp... int numRaw = 0; //iteramos la lista for (int i = 0; i < pList.size(); ++i) { qulonglong c = pList.at(i); ProductInfo pInfo = myDb->getProductInfo(QString::number(c)); if (pInfo.isARawProduct) numRaw++; if (pInfo.code==0 || pInfo.isARawProduct) continue; //discard this item, continue loop. //insert each product to the search table... int rowCount = ui_mainview.tableSearch->rowCount(); ui_mainview.tableSearch->insertRow(rowCount); QTableWidgetItem *tid = new QTableWidgetItem(pInfo.desc); if (pInfo.stockqty == 0) { QBrush b = QBrush(QColor::fromRgb(255,100,0), Qt::SolidPattern); tid->setBackground(b); } else if (pInfo.stockqty > 0 && pInfo.stockqty < Settings::stockAlertValue() ) {//NOTE:This must be shared between iotpos and iotstock QBrush b = QBrush(QColor::fromRgb(255,176,73), Qt::SolidPattern); tid->setBackground(b); } ui_mainview.tableSearch->setItem(rowCount, 0, tid); //NOTE:bug fixed Sept 26 2008: Without QString::number, no data was inserted. // if it is passed a numer as the only parameter to QTableWidgetItem, it is taken as a type // and not as a data to display. double finalPrice = pInfo.price; if (Settings::addTax()) finalPrice += pInfo.totaltax; ui_mainview.tableSearch->setItem(rowCount, 1, new QTableWidgetItem(QString::number(pInfo.price, 'f', 2))); ui_mainview.tableSearch->setItem(rowCount, 2, new QTableWidgetItem(QString::number(finalPrice, 'f', 2))); //price with taxes ui_mainview.tableSearch->setItem(rowCount, 3, new QTableWidgetItem(QString::number(pInfo.stockqty))); //STOCK Level ui_mainview.tableSearch->setItem(rowCount, 4, new QTableWidgetItem(pInfo.alphaCode)); //Alphacode ui_mainview.tableSearch->setItem(rowCount, 5, new QTableWidgetItem(QString::number(pInfo.code))); } if (pList.count()>0) ui_mainview.labelSearchMsg->setText(i18np("%1 item found","%1 items found.", pList.count()-numRaw)); else ui_mainview.labelSearchMsg->setText(i18n("No items found.")); delete myDb; resizeSearchTable(); } int iotposView::getItemRow(QString c) { int result = 0; for (int row=0; row<ui_mainview.tableWidget->rowCount(); ++row) { QTableWidgetItem * item = ui_mainview.tableWidget->item(row, colCode); QString icode = item->data(Qt::DisplayRole).toString(); if (icode == c) { result = row; break; } } return result; //0 if not found } void iotposView::refreshTotalLabel() { buyPoints = 0; //BEGIN of REWRITE: This code has been rewritten from scratch, again. DEC 18 2011. totalSum = 0; totalTax = 0; totalSumWODisc = 0; //used to calculate (informative only) discount on method updateClientInfo() discMoney = 0; globalDiscount = 0; double sum = 0.0; double taxes = 0.0; double totalTaxP = 0.0; //total tax percentage, calculated after tax sum is calculated, totalTaxP = taxes/sum int nonDiscountables = 0; double gDiscountPercentage = 0; bool roundToUSStandard = Settings::roundToUSStandard(); bool extractTaxes = !Settings::addTax(); //just a better name to understant what to do. bool notApply = false; Azahar *myDb = new Azahar; myDb->setDatabase(db); ///If we are dealing with a reservation, then we do not need to calculate any totals; we already have it on the reservation info. // FIXME: The only problem with this is that we DONT know if there was a price-change to an item because it is not RECORDED at the reservation or transaction. if (reservationPayment > 0) { //we need to double check the reservation payment. ReservationInfo rInfo = myDb->getReservationInfoFromTr( currentTransaction ); if (rInfo.id > 0 && rInfo.transaction_id > 0 && rInfo.transaction_id == currentTransaction) { qDebug()<<" Ok, this is a reservation. Tr #:"<<currentTransaction<<" Reservation #:"<<rInfo.id<<" Reservation Payment:"<<rInfo.payment<<" Reservation Total:"<<rInfo.total; reservationPayment = rInfo.payment; //Now set totals according. This is due to the fact that items here could be changed its price. totalTax = rInfo.totalTaxes; //the taxes are included only at the reservation final payment. subTotalSum = rInfo.total - reservationPayment; } else { //The currentTransaction does not have a reservation; reset reservationPayment. qDebug()<<"The tr #"<<currentTransaction<<" Is not reserved. ReservationPayment of "<<reservationPayment<<" is invalid; resetting to 0."; reservationPayment = 0; } } //BEGIN no special Orders if ( specialOrders.isEmpty() && reservationPayment <= 0 ) foreach(ProductInfo prod, productsHash) { if (prod.isNotDiscountable) { nonDiscountables++; } double iPrice = prod.price; //one item double iTaxM = 0; //if item has discount, apply it. if (!prod.validDiscount && prod.disc > 0 && !prod.isNotDiscountable) ///if this is true, then there is a product price change. iPrice -= prod.disc; if (!prod.validDiscount && prod.disc < 0 && !prod.isNotDiscountable) ///if this is true, then there is a product price change. iPrice -= prod.disc; if (prod.validDiscount && !prod.isNotDiscountable) iPrice -= (prod.discpercentage/100)*iPrice; //prod.price; because the price could be changed. if ( gDiscountPercentage > 0 ) //apply general discount. gDiscountPercentage is in PERCENTAGE Already... do not divide by 100. iPrice -= (gDiscountPercentage)*iPrice; /// prod.price NOTE: if gDiscountPercentage is greater than 1 then it will produce negative price! if (extractTaxes) iTaxM = iPrice - (iPrice/(1+((prod.tax+prod.extratax)/100))); //one item else iTaxM = iPrice * ((prod.tax+prod.extratax)/100); //one item sum += iPrice * prod.qtyOnList; taxes += iTaxM * prod.qtyOnList; buyPoints += prod.points * prod.qtyOnList; totalSumWODisc += (iPrice+iTaxM) * prod.qtyOnList; //WARNING: check this!: It will be used for informatavie purpose. qDebug()<<prod.desc<<" -> Price without Tax:"<<iPrice<<" item Tax $:"<<iTaxM<<" Accumulated Tax in the purchase $:"<<taxes<< " Sum:"<<sum; } //for each product //END no special orders //After inspecting each product or special order or reservation then continue with total global discounts, subtotal and total. if ((nonDiscountables == productsHash.count() && !productsHash.isEmpty()) || (nonDiscountables == specialOrders.count() && !specialOrders.isEmpty() )) notApply = true; //now we can calculate total tax percentage. This is an "average" tax of the whole sale. if (taxes >0 && sum >0) //to avoid a NaN result totalTaxP = taxes/sum; // example, 10/100 = .10 => means 10 percent tax ///Now we need to get and apply GENERAL DISCOUNTS (applied to the whole sale) like client discount or ocassional discounts. //NOTE: What about reservations? double gDiscount = 0; //in money. if (clientInfo.discount >0 && !notApply) gDiscountPercentage = clientInfo.discount/100; if (oDiscountMoney > 0 && !notApply) gDiscount = oDiscountMoney; //get the DOLLAR discount in percentage. Here, the global discount has precedence over the client discount. if (gDiscount > 0 && sum > 0) //if 0, it means the gDiscountPercentage is already calculated in previous steps... or is really 0. gDiscountPercentage = gDiscount/sum; if (gDiscountPercentage > 0) discMoney = gDiscountPercentage * sum; globalDiscount = gDiscountPercentage; //global variable. qDebug()<<"[*] discMoney: "<<discMoney<<" gDiscount:"<<gDiscount<<" gDiscountPercentage:"<<gDiscountPercentage<<" TotalTaxP:"<<totalTaxP; //apply global discounts to the sum. sum -= sum * gDiscountPercentage; ///we get subtotal. if (reservationPayment <= 0) { subTotalSum = sum - reservationPayment; // discount applied some lines above. totalTax = totalTaxP * sum; } //else this are calculated before when getting rInfo. if (Settings::addTax()) totalSum = subTotalSum + totalTax; else totalSum = subTotalSum; //we get change double paid, change; bool isNum; paid = ui_mainview.editAmount->text().toDouble(&isNum); if (isNum) change = paid - totalSum; else change = 0.0; if (paid <= 0) change = 0.0; qDebug()<<"[*] Sum (w/discounts):"<<sum<<" subTotal:"<<subTotalSum<<" totalTax:"<<totalTax<<" TOTAL SUM:"<<totalSum<<" Tendered:"<<paid<<" CHANGE:"<<change; roundToUSStandard = false; //FIXME: disabled now, sometimes it is not good (+/-) if ( roundToUSStandard ) { //first round taxes RoundingInfo rTotalTax = roundUsStandard(totalTax); //then round subtotal RoundingInfo rSubTotalSum = roundUsStandard(subTotalSum); //then round total RoundingInfo rTotalSum = roundUsStandard(totalSum); ///NOTE: discount must not be rounded!.. example: total= 2.95 -> 3.0 discount= 0.5 => 1.0, grand total= 3-1 = 2 and should be 2.90. //then round change RoundingInfo rChange = roundUsStandard(change); //assigning them. totalTax = rTotalTax.doubleResult; subTotalSum = rSubTotalSum.doubleResult; totalSum = rTotalSum.doubleResult; change = rChange.doubleResult; //NOTE: When rounding the change it could be tricky if we play beyond reality. // Example: paid: 109.91 (which it never should hapen because $.01 coins does not exists, right?) // purchase: 109.75 rounding gets 109.80 // so, the change before rounding is 0.15 (109.91 - 109.80) , rounding is 0.20. // But if instead of paying 109.91, a more real payment is 109.90; // the change before rounding is 0.14, rounding is 0.10 which is correct. } ///refresh labels. BasketPriceSummary summary = recalculateBasket(oDiscountMoney); if (isNum) { change = paid - summary.getGross().toDouble(); } else { change = 0.0; } ui_mainview.labelTotal->setText(QString("%1").arg(KGlobal::locale()->formatMoney(summary.getGross().toDouble()))); ui_mainview.lblSubtotal->setText(QString("%1").arg(KGlobal::locale()->formatMoney(summary.getNet().toDouble()+summary.getDiscountGross().toDouble())));//FIXME temporal, seems than gross and net are equal without + summary.getDiscountGross().toDouble() ui_mainview.labelChange->setText(QString("%1") .arg(KGlobal::locale()->formatMoney(change))); ui_mainview.labelTotalDiscount->setText(QString("%1") .arg(KGlobal::locale()->formatMoney(summary.getDiscountGross().toDouble()))); if (summary.getDiscountGross().toDouble() == 0 && !ui_mainview.labelTotalDiscount->isHidden()){ ui_mainview.labelTotalDiscountpre->hide(); ui_mainview.labelTotalDiscount->hide(); } else if (summary.getDiscountGross().toDouble() > 0){ ui_mainview.labelTotalDiscountpre->show(); ui_mainview.labelTotalDiscount->show(); } ui_mainview.lblSaleTaxes->setText(QString("%1") .arg(KGlobal::locale()->formatMoney(summary.getTax().toDouble()))); ///update client discount //QString dStr; //if (clientInfo.discount >0) { // dStr = i18n("Discount: %1% [%2]",clientInfo.discount, KGlobal::locale()->formatMoney(discMoney)); //} else if (oDiscountMoney >0 ){ // dStr = i18n("Discount: %1", KGlobal::locale()->formatMoney(oDiscountMoney)); //} updateClientInfo(); if ( ui_mainview.checkOwnCredit->isChecked() || ui_mainview.checkCard->isChecked() ) { //Set the amount to pay. ui_mainview.editAmount->setText(QString::number(totalSum, 'f', 2)); } //inform the user if the discount cannot be applied. if (notApply && (gDiscount > 0 || gDiscountPercentage>0)) { ///WARNING: Problem when SO contains one non discountable item, and two or more SOs. REVIEW THIS CASE! notifierPanel->setSize(350,150); notifierPanel->setOnBottom(false); notifierPanel->showNotification("<b>Cannot apply discount</b> to a product marked as not discountable.",5000); } gTaxPercentage = totalTaxP; //saving global tax percentage. delete myDb; //END of Rewrite } RoundingInfo iotposView::roundUsStandard(const double &number) { RoundingInfo result; result.doubleResult = 0.0; result.intIntPart = 0; result.intDecPart = 0; result.strResult = "0.0"; if (number == 0.0) return result; QString num = QString::number(number, 'f', 2 ); //round to two decimal places first and get a string. The number is represented as INT_PART.XX QString decPart = num.right(2); //last two digits are the decimal part. num.chop(3); //remove last 2 digits and decimals separator. DO NOT USE num any more to get data from the whole number QString intPart = num; QString newDecPart = "00"; //we will fill this number // X1 -> X4 rounds down to X0 // X5 -> X9 rounds up to (X+1)0 //Example: 22 rounds down to 20, 68 rounds up to 70 QString ldDecPart = decPart.right(1); //last decimal part QString fdDecPart = decPart.left(1); //first decimal part int iLdDecPart = ldDecPart.toInt(); int iFdDecPart = fdDecPart.toInt(); int intIntPart = intPart.toInt(); //We need to examine the last digit in the decPart. decPart is two digits (ex: 01, 78, 99) if ( iLdDecPart == 0 ) newDecPart = fdDecPart+"0"; // no rounding.. else if ( iLdDecPart > 0 && iLdDecPart < 5) newDecPart = fdDecPart+"0"; // rounds down to X0. No further checks else { // rounds up to (X+1)0. Further checks to see if the INT_PART needs an increment ( example: 1.98 rounds to 2.00 ) int xPlusOne = iFdDecPart+1; if ( xPlusOne > 9 ){ newDecPart = "00"; // rounds up to .00 intIntPart += 1; // INT_PART+1 } else { newDecPart = QString::number( xPlusOne )+"0"; } //qDebug()<<"fdDecPart:"<<fdDecPart<<"iFdDecPart:"<<iFdDecPart<<"xPlusOne:"<<xPlusOne; } QString newIntPart = QString::number( intIntPart ); int intNewDecPart = newDecPart.toInt(); result.intIntPart = intIntPart; result.intDecPart = intNewDecPart; result.strResult = newIntPart + "." + newDecPart; //Here using a DOT as decimal separator. FIXME: Use locale to get the decimal separator. But KLocale formatMoney/Number can do it from the result.doubleResult. result.doubleResult = (result.strResult).toDouble(); qDebug()<<__FUNCTION__<<"Original number: "<<number<<"doubleResult:"<<result.doubleResult<<" strResult:"<<result.strResult<<" | intIntPart:"<<result.intIntPart<<" intDecPart:"<<result.intDecPart; return result; } void iotposView::doEmitSignalQueryDb() { emit signalQueryDb(ui_mainview.editItemCode->text()); } bool iotposView::incrementTableItemQty(QString code, double q) { double qty = 1; double discount_old=0.0; double qty_old=0.0; double stockqty=0; bool done=false; ProductInfo info; if (productsHash.contains(code.toULongLong())) { //get product info... info = productsHash.value(code.toULongLong()); stockqty = info.stockqty; qty = info.qtyOnList; qty_old = qty; QStringList itemsNotAvailable; bool allowNegativeStock = Settings::allowNegativeStock(); bool overSelling = false; QString msg; //stock qty for groups are different. NEW: Take into account the negative stock settings. bool available = true; if (info.isAGroup) { Azahar *myDb = new Azahar; myDb->setDatabase(db); QStringList lelem = info.groupElementsStr.split(","); foreach(QString ea, lelem) { qulonglong c = ea.section('/',0,0).toULongLong(); double qq = ea.section('/',1,1).toDouble(); ProductInfo pi = myDb->getProductInfo(QString::number(c)); QString unitStr; bool yes = false; double onList = getTotalQtyOnList(pi); // item itself and contained in any gruped product. // q : item qty to add. // qq : item qty on current grouped element to add // qq*q : total items to add for this product. // onList: items of the same product already on the shopping list. if (pi.stockqty >= ((qq*q)+onList) ) yes = true; available = (available && yes ); if (!yes && !allowNegativeStock ) { itemsNotAvailable << i18n("%1 has %2 %3 but requested %4 + %5",pi.desc,pi.stockqty,unitStr,qq*q,onList); } qDebug()<<pi.desc<<" qtyonstock:"<<pi.stockqty<<" needed qty (onlist and new):"<<QString::number((qq*q)+onList); //New: if allowNegativeStock, then allow it anyway. FIXME: TEST THIS!!!!!! Grouped products with allowNegativeStock. also for inserting. if (allowNegativeStock) available = true; if (pi.stockqty >= ((qq*q)+onList)) overSelling=false; else overSelling = true; if (overSelling && available) msg += i18n("<html><font color=red>The product you requested %1 articles <b>has a negative or zero stock level.</b></font></html>", ((qq*q)+onList)); } delete myDb; } else { double onList = getTotalQtyOnList(info); // item itself and contained in any gruped product. if (stockqty >= q+onList) available = true; else {available = false; overSelling = true;} if (allowNegativeStock) available = true; qDebug()<<info.desc<<" qtyonstock:"<<info.stockqty<<" needed qty (onlist and new):"<<QString::number(q+onList)<<" Allow NegativeStock:"<<allowNegativeStock; } if (available) { qty+=q; if (overSelling) //FIXME: msg += is for the case when grouped products has some not available product. msg += i18n("<html><font color=red>The product you requested %1 articles <b>has a negative or zero stock level.</b></font></html>", qty); } else { double onList = getTotalQtyOnList(info); // item itself and contained in any gruped product. if (!itemsNotAvailable.isEmpty()) msg = i18n("<html><font color=red><b>The group/pack is not available because:<br>%1</b></font></html>", itemsNotAvailable.join("<br>")); else msg = i18n("<html><font color=red><b>There are only %1 articles of your choice at stock.<br> You requested %2</b></font></html>", info.stockqty,q+onList); if (ui_mainview.mainPanel->currentIndex() == pageSearch) { ui_mainview.labelSearchMsg->setText(msg); ui_mainview.labelSearchMsg->show(); QTimer::singleShot(3000, this, SLOT(clearLabelSearchMsg()) ); } } if ( ui_mainview.mainPanel->currentIndex() == pageMain && !msg.isEmpty() ) { ui_mainview.editItemCode->clearFocus(); tipCode->showTip(msg, 6000); } QTableWidgetItem *itemQ = ui_mainview.tableWidget->item(info.row, colQty);//item qty itemQ->setData(Qt::EditRole, QVariant(qty)); done = true; QTableWidgetItem *itemD = ui_mainview.tableWidget->item(info.row, colDisc);//item discount discount_old = itemD->data(Qt::DisplayRole).toDouble(); //calculate new discount double discountperitem = (discount_old/qty_old); double newdiscount = discountperitem*qty; itemD->setData(Qt::EditRole, QVariant(newdiscount)); //qDebug()<<"incrementTableQty... old discount:"<<discount_old<<" old qty:"<<qty_old<<" new discount:"<<newdiscount<<"new qty:"<<qty<<" disc per item:"<<discountperitem; done = true; info.qtyOnList = qty; productsHash.remove(code.toULongLong()); productsHash.insert(info.code, info); //display new info on the purchase list. updateItem(info); refreshTotalLabel(); QTableWidgetItem *item = ui_mainview.tableWidget->item(info.row, colCode);//item code displayItemInfo(item); //TODO: Cambiar para desplegar de ProductInfo. if (QApplication::keyboardModifiers().testFlag(Qt::ControlModifier) == false) { ui_mainview.editItemCode->clear(); } } //if productsHash.contains... return done; } void iotposView::insertItem(QString code) { QRegExp rL("[A-Z]"); QRegExp rl("[a-z]"); //QRegExp rds("^\\d\\d\\d\\d.\\d\\d?$"); //QRegExp rds("^\\d\\d\\d?$"); QRegExp rds("^-\\d+$"); //qDebug() << code; // qDebug() << rl.indexIn(code) << " " << rL.indexIn(code) ; //qDebug() << " HOLA ---------" << rds.indexIn(code) ; //qDebug() << "INSERTITEM --------- " << code; if (ui_mainview.editItemCode->text()=="*" || ui_mainview.editItemCode->text()=="") { productsModel->setFilter("products.isARawProduct=false"); } if((rl.indexIn(code) < 0) && (rL.indexIn(code) < 0) && rds.indexIn(code) < 0 ){ if ( code.isEmpty() || code == "0" || code.startsWith("0*") || code.endsWith("0.")) { ui_mainview.editItemCode->clear(); return; } if ( !specialOrders.isEmpty() ) { KNotification *notify = new KNotification("information", this); notify->setText(i18n("Only Special Orders can be added. Please finish the current special order before adding any other product.")); QPixmap pixmap = DesktopIcon("dialog-information",32); notify->setPixmap(pixmap); notify->sendEvent(); ui_mainview.editItemCode->clear(); return; } qDebug()<< __FUNCTION__ <<" doNotAddMoreItems = "<<doNotAddMoreItems; if ( doNotAddMoreItems ) { //only for reservations KNotification *notify = new KNotification("information", this); notify->setText(i18n("Cannot Add more items to the Reservation.")); QPixmap pixmap = DesktopIcon("dialog-information",32); notify->setPixmap(pixmap); notify->sendEvent(); ui_mainview.editItemCode->clear(); return; } double qty = 1; bool qtyWritten = false; QString codeX = code; ProductInfo info; info.code = 0; info.desc = "[INVALID]"; //now code could contain number of items to insert,example: 10*1234567890 QStringList list = code.split(QRegExp("[//*]{1,1}"),QString::SkipEmptyParts); if (list.count()==2) { qty = list.takeAt(0).toDouble(); codeX = list.takeAt(0); qtyWritten = true; } Azahar *myDb = new Azahar; myDb->setDatabase(db); //Now ClientsID can be entered in the product editline for speed up clients selection. //There are two ways of identifying clients. // 1.- By using a 6 digit (UPC-E) barcode (code). Discarding any product with 6 digits code. // 2.- By using a 12/13 (UPC/EAN) barcode (code). Discarding any 12/13 digits code starting with "4". // -A case where a qty (2*XXXXXX) is entered can bypass this client identification. So we know a product will be entered and not a client id. if (Settings::groupUserIdAsCode() && !qtyWritten ) { bool clientFound = false; bool check=false; ClientInfo cI; if (!specialOrders.isEmpty()) { notifierPanel->setSize(350,150); notifierPanel->setOnBottom(false); notifierPanel->showNotification(i18n("Cannot change customer while Special Orders are in Purchase.",codeX),4000); ui_mainview.editItemCode->clear(); ui_mainview.editItemCode->setFocus(); setupGridView(); return; } if (Settings::rb6Digits() && codeX.length() == 6) { //A 6 digit code for Customer ID. cI = myDb->getClientInfo(codeX); check = true; if (cI.id >0) clientFound = true; } else if (codeX.length() >11 && codeX.startsWith("4")){ //A 12/13 digit code for Customer ID Starting with "4". check = true; cI = myDb->getClientInfo(codeX); if (cI.id >0) clientFound = true; } else check = false; // no 6digit or 12digit code configured, //Check for products any way? if (check) { if (clientFound) { QString msg; clientInfo = cI; //get client Remaining credit (-) to inform the client. CreditInfo credit = myDb->getCreditInfoForClient(cI.id); if (credit.total <= 0) //if it is negative then inform. msg = i18n("<b>Welcome</b> <i>%1</i>. You have remaining <b>debit</b> of %2 to use.",clientInfo.name, KGlobal::locale()->formatMoney(-credit.total)); else msg = i18n("<b>Welcome</b> <i>%1</i>. You have remaining <b>credit</b> of %2 used.",clientInfo.name, KGlobal::locale()->formatMoney(-credit.total)); updateClientInfo(); refreshTotalLabel(); notifierPanel->setSize(350,150); notifierPanel->setOnBottom(false); notifierPanel->showNotification(msg,4000); ui_mainview.editItemCode->clear(); ui_mainview.editItemCode->setFocus(); setupGridView(); return; } else { notifierPanel->setSize(350,150); notifierPanel->setOnBottom(false); notifierPanel->showNotification(i18n("No Customer found with code %1.",codeX),4000); ui_mainview.editItemCode->clear(); ui_mainview.editItemCode->setFocus(); setupGridView(); return; } }//if check... }//if config for client identification //Here there are barcodes that support weight. Such products begin with a 2 and its length is 13. ///@link http://en.wikipedia.org/wiki/Universal_Product_Code#Prefixes qDebug()<<" EXAMINING PRODUCT CODE "<<codeX; if ( codeX.length() == 13 && codeX.startsWith("2") ) { ///This is a weighted product, such as meat and fruits... //get the weight, which is at positions RRRRRR of the code ( SLLLLLLMRRRRRRE ). QString pWeight = codeX.right(6); pWeight = pWeight.remove(5, 1); if (pWeight.length() == 5) { //add the decimal point... pWeight.insert(2, "."); qty = pWeight.toDouble(); //convert weight to QTY. } ///now, exclude the weight from the codeX. NOTE: Document THIS! codeX = codeX.left(7); // only the first 7 digits, the first digit is the prefix, which must be '2'. //NOTE: Here, the prefix is considered to be part of the product code. qDebug()<<" New codeX:"<<codeX<<" weight:"<<pWeight<<" Double weight:"<<qty; } bool allowNegativeStock = Settings::allowNegativeStock(); QString msg; info = myDb->getProductInfo(codeX); //includes discount and validdiscount qDebug()<<" CodeX = "<<codeX<<" Numeric Code:"<<info.code<<" Alphacode:"<<info.alphaCode<<"QtyOnList:"<<info.qtyOnList<<" Required Qty:"<<qty<<" Allow NegativeStock:"<<allowNegativeStock; //the next 'if' checks if the hash contains the product and got values from there.. To include purchaseQty, that we need! if (productsHash.contains( info.code )) { info = productsHash.value( info.code ); } //verify item units and qty.. if (info.units == uPiece) { unsigned int intqty = qty; if ( qty-intqty > 0 ) { //quantities are different, and its a fraction.. like 0.5 or 1.2 msg = i18n("The requiered qty is %1 and its not allowed for the required product, please verify the quantity", qty); if (intqty <= 0) { //Because below there is a return if qty<=0 ui_mainview.editItemCode->clearFocus(); tipCode->showTip(msg, 6000); } } qty = intqty; } if ( qty <= 0) {return;} ///Bundle procedure. /// A product can be added to a bundle when at the bundle_same table exists qty for the amount required. /// Example: A bundle for product 501: /// Qty: 2, Price: 5 /// Qty: 3, Price: 4.5 /// Qty: 4, Price: 4 /// So, if in the hash exists 4x501 and another is added (incremented) then the product cannot be added to the bundle, it needs to form another bundle when another is added (2+) ///------------------------------------------------------------------------------------------------------------------------------------ /// Is product in the hash? YES -> Is any bundle containing it? YES -> Can be added to it? YES -> Add to bundle -> Add to hash /// NO -> Add to hash /// NO -> Create Bundle -> Add to bundle -> Add to hash /// NO -> Add to hash if ( productsHash.contains(info.code) ) { //Insert the bundle... int tQty = 0; if (info.qtyOnList == 1) tQty = 1; //if there is ONE item at the productsHash then we need to add 1 because the first one was not added. BundleInfo bundle; BundleInfo maxBundled = myDb->getMaxBundledForProduct(info.code); //gets the maximum qty and price for this product bundle. bundle.product_id = info.code; bundle.qty = qty + tQty; bundle.price = myDb->getBundlePriceFor(info.code); //FIXME: we need a price for each qty on each bundle inserted.. this is going to be at the BundleList class! qDebug()<<"Going to insert "<<bundle.qty<<" items."<<" info.qtyOnList:"<<info.qtyOnList; bundlesHash->addItem(bundle, maxBundled.qty); bundlesHash->debugAll(); } delete myDb; if (!incrementTableItemQty( QString::number(info.code) /*codeX*/, qty) ) { info.qtyOnList = qty; bool overSelling = false; int insertedAtRow = -1; bool productFound = false; if ( info.code > 0 ) productFound = true; if ( info.isARawProduct ) productFound = false; double descuento=0.0; if (info.validDiscount) descuento = info.disc*qty; if ( !productFound ) { msg = i18n("<html><font color=red><b>Product not found in database.</b></font></html>"); } else if ( productFound ) { //NOW CHECK IF ITS A GROUP QString iname = info.desc; if (info.isAGroup ) { QStringList itemsNotAvailable; if (!info.groupElementsStr.isEmpty()) { Azahar *myDb = new Azahar; myDb->setDatabase(db); bool available = true; QStringList lelem = info.groupElementsStr.split(","); foreach(QString ea, lelem) { qulonglong c = ea.section('/',0,0).toULongLong(); double q = ea.section('/',1,1).toDouble(); ProductInfo pi = myDb->getProductInfo(QString::number(c)); QString unitStr; if (pi.units == 1 ) unitStr=" "; else unitStr = pi.unitStr; iname += '\n' + QString::number(q) + " "+ unitStr +" "+ pi.desc; bool yes = false; double onList = getTotalQtyOnList(pi); // item itself and contained in any gruped product. // q : item qty to add. // qq : item qty on current grouped element to add // q*qty : total items to add for this product. // onList: items of the same product already on the shopping list. if (pi.stockqty >= ((q*qty)+onList) ) yes = true; available = (available && yes ); if (!yes && !allowNegativeStock) { itemsNotAvailable << i18n("%1 has %2 %3 but requested %4 + %5",pi.desc,pi.stockqty,unitStr,qty*q,onList); } qDebug()<<pi.desc<<" qtyonstock:"<<pi.stockqty<<" needed qty:"<<QString::number(qty*q); //New: if allowNegativeStock, then allow it anyway. if (allowNegativeStock) available = true; if (pi.stockqty >= ((q*qty)+onList)) overSelling=false; else overSelling = true; if (overSelling && available) msg += i18n("<html><font color=red>The product you requested %1 articles <b>has a negative or zero stock level.</b></font></html>", ((q*qty)+onList)); } //CHECK AVAILABILITY OR ALLOWNEGATIVESTOCK if (available || availabilityDoesNotMatters || allowNegativeStock) { if (availabilityDoesNotMatters) qDebug() << __FUNCTION__ <<" Availability DOES NOT MATTERS! "; insertedAtRow = doInsertItem( QString::number(info.code) /*codeX*/, iname, qty, info.price, descuento, info.unitStr); } else msg = i18n("<html><font color=red><b>The group/pack is not available because:<br>%1</b></font></html>", itemsNotAvailable.join("<br>")); delete myDb; } } else { //It is not a grouped product double onList = getTotalQtyOnList(info); // item itself and contained in any gruped product. if (info.stockqty >= qty+onList) overSelling = false; else overSelling = true; if (info.stockqty >= qty+onList || availabilityDoesNotMatters || allowNegativeStock) { if (availabilityDoesNotMatters) qDebug() << __FUNCTION__ <<" Availability DOES NOT MATTERS! "; insertedAtRow = doInsertItem( QString::number(info.code) /*codeX*/, iname, qty, info.price, descuento, info.unitStr); if (overSelling) msg = i18n("<html><font color=red>The product you requested %1 articles <b>has a negative or zero stock level.</b></font></html>", qty+onList); } else msg = i18n("<html><font color=red><b>There are only %1 articles of your choice at stock.<br> You requested %2</b></font></html>", info.stockqty,qty+onList); } } else qDebug()<<"\n\n***Este ELSE no importa!!! ya se tomaron acciones al respecto***\nTHIS SHOULD NOT BE PRINTED!!!\n\n"; if (allowNegativeStock && info.stockqty < qty && info.code > 0) //we are inserting the product the first time, so no onlist.FIXME: check for group case. msg = i18n("<html><font color=red>The product you requested %1 articles <b>has a negative or zero stock level.</b></font></html>", qty); qDebug()<<"AllowNegativeStock:"<<allowNegativeStock<<" info.stockqty:"<<info.stockqty<<" qty:"<<qty; if (!msg.isEmpty()) { if (ui_mainview.mainPanel->currentIndex() == pageMain) { ui_mainview.editItemCode->clearFocus(); tipCode->showTip(msg, 10000); } if (ui_mainview.mainPanel->currentIndex() == pageSearch) { ui_mainview.labelSearchMsg->setText(msg); ui_mainview.labelSearchMsg->show(); QTimer::singleShot(3000, this, SLOT(clearLabelSearchMsg()) ); } ui_mainview.editItemCode->clear(); } info.row = insertedAtRow; if (info.row >-1 && info.desc != "[INVALID]" && info.code>0){ productsHash.insert(info.code /*codeX.toULongLong()*/, info); QTableWidgetItem *item = ui_mainview.tableWidget->item(info.row, colCode); displayItemInfo(item); refreshTotalLabel(); } }//if !increment... //Saving session. qDebug()<<"** INSERTING A PRODUCT [updating balance/transaction]"; updateBalance(false); updateTransaction(); if (ui_mainview.rbFilterByDesc->isChecked()) { ui_mainview.editItemCode->setFocus();//by description if (QApplication::keyboardModifiers().testFlag(Qt::ControlModifier) == false){ productsModel->setFilter("products.isARawProduct=false"); //productsModel->setFilter("products.isARawProduct=false and (products.datelastsold > ADDDATE(sysdate( ), INTERVAL -31 DAY )) ORDER BY products.datelastsold DESC "); } } else { if (ui_mainview.rbFilterByCategory->isChecked()) { //by category ui_mainview.frameGridView->show(); //Find catId for the text on the combobox. int catId=-1; QString catText = ui_mainview.comboFilterByCategory->currentText(); if (categoriesHash.contains(catText)) { catId = categoriesHash.value(catText); } productsModel->setFilter(QString("products.isARawProduct=false and products.category=%1").arg(catId)); } // else { //by most sold products in current month --biel // productsModel->setFilter("products.isARawProduct=false and (products.datelastsold > ADDDATE(sysdate( ), INTERVAL -31 DAY )) ORDER BY products.datelastsold DESC LIMIT 20"); //limit or not the result to 5? // } } } else if ( rl.indexIn(code) == 0 || rL.indexIn(code) == 0 ) { QRegExp regexp = QRegExp(code); if (!regexp.isValid()) ui_mainview.editItemCode->setText(""); if (ui_mainview.editItemCode->text()=="*" || ui_mainview.editItemCode->text()=="") productsModel->setFilter("products.isARawProduct=false ORDER BY products.datelastsold DESC"); else productsModel->setFilter(QString("products.isARawProduct=false and products.name REGEXP '%1'").arg(ui_mainview.editItemCode->text())); ui_mainview.frameGridView->show(); productsModel->select(); } else if (rds.indexIn(code) == 0) { QString codeWOSing = code.remove(0,1); productsModel->setFilter(QString("products.isARawProduct=false and products.price=%1").arg(codeWOSing)); ui_mainview.frameGridView->show(); } refreshTotalLabel(); ui_mainview.tableWidget->scrollToBottom(); }//insertItem double iotposView::getTotalQtyOnList(const ProductInfo &info) { double result = 0; //first inspect the products hash to see how many direct products are there, then if any group contains foreach (ProductInfo pi, productsHash) { //first direct products. if (pi.code == info.code) { result += pi.qtyOnList; qDebug()<<"Found product "<<info.code<<" with "<<pi.qtyOnList<<" items in shopping list."; } else { //so its not the product itself, maybe its a group containing it if (pi.isAGroup) { QStringList lelem = pi.groupElementsStr.split(","); foreach(QString ea, lelem) { qulonglong c = ea.section('/',0,0).toULongLong(); double qq = ea.section('/',1,1).toDouble(); if (c == info.code) { //YES its contained in this group double qqq = qq*pi.qtyOnList; result += qqq; qDebug()<<" Found product "<<info.code<<" on grouped product "<<c<<" containing "<<qqq<<" items"; } } } } //it was a group } return result; } void iotposView::updateItem(ProductInfo prod) { QTableWidgetItem *item = ui_mainview.tableWidget->item(prod.row, colCode); displayItemInfo(item); //check if discounts double itemDiscount = 0; if (prod.disc > 0 || prod.disc < 0 || (prod.discpercentage > 0 && prod.validDiscount) ) { if ((prod.disc > 0 || prod.disc < 0) && !prod.validDiscount) itemDiscount += prod.disc; //price change if ( prod.discpercentage > 0 && prod.validDiscount ) itemDiscount += (prod.discpercentage/100)*prod.qtyOnList; //item offer } if (itemDiscount < 0) { //item changed price to higer. So do not say it is a discount. item = ui_mainview.tableWidget->item(prod.row, colDisc); item->setData(Qt::EditRole, "0.0"); item = ui_mainview.tableWidget->item(prod.row, colPrice); item->setData(Qt::EditRole, QVariant(prod.price-itemDiscount)); } else { item = ui_mainview.tableWidget->item(prod.row, colDisc); QBrush b = QBrush(QColor::fromRgb(0,0,0), Qt::SolidPattern); //it used to paint RED the discount cell after more than 1 item added item->setForeground(b); item->setData(Qt::EditRole, QVariant(itemDiscount)); //when the item has a previous price change to higer price, the price then is changed //so if after applying this kind of change price, the price is set lower again, then we //need to change the price according. item = ui_mainview.tableWidget->item(prod.row, colPrice); item->setData(Qt::EditRole, QVariant(prod.price)); //set the original price. } //update QTY (this code is reused) item = ui_mainview.tableWidget->item(prod.row, colQty); item->setData(Qt::EditRole, QVariant(prod.qtyOnList)); //now update product total item = ui_mainview.tableWidget->item(prod.row, colDue); if (itemDiscount > 0) { QBrush b = QBrush(QColor::fromRgb(255,0,0), Qt::SolidPattern); item->setForeground(b); } //we modified discount per item, so now multiply by item qty to update the final price with discount. dec 10 2011. itemDiscount = itemDiscount*prod.qtyOnList; item->setData(Qt::EditRole, QVariant((prod.qtyOnList*prod.price)-itemDiscount)); ui_mainview.tableWidget->resizeRowsToContents(); } int iotposView::doInsertItem(QString itemCode, QString itemDesc, double itemQty, double itemPrice, double itemDiscount, QString itemUnits) { int rowCount = ui_mainview.tableWidget->rowCount(); ui_mainview.tableWidget->insertRow(rowCount); ui_mainview.tableWidget->setItem(rowCount, colCode, new QTableWidgetItem(itemCode)); ui_mainview.tableWidget->setItem(rowCount, colDesc, new QTableWidgetItem(itemDesc)); ui_mainview.tableWidget->setItem(rowCount, colPrice, new QTableWidgetItem(""));//must be empty for HACK ui_mainview.tableWidget->setItem(rowCount, colQty, new QTableWidgetItem(QString::number(itemQty))); ui_mainview.tableWidget->setItem(rowCount, colUnits, new QTableWidgetItem(itemUnits)); ui_mainview.tableWidget->setItem(rowCount, colDisc, new QTableWidgetItem(""));//must be empty for HACK ui_mainview.tableWidget->setItem(rowCount, colDue, new QTableWidgetItem(""));//must be empty for HACK QTableWidgetItem *item = ui_mainview.tableWidget->item(rowCount, colDisc); if (itemDiscount>0) { QBrush b = QBrush(QColor::fromRgb(255,0,0), Qt::SolidPattern); item->setForeground(b); } //HACK:The next 4 lines are for setting numbers with comas (1,234.00) instead of 1234.00. // seems to be an effect of QVariant(double d) item->setData(Qt::EditRole, QVariant(itemDiscount)); item = ui_mainview.tableWidget->item(rowCount, colDue); //item->setData(Qt::EditRole, QVariant(itemQty*(itemPrice-itemDiscount))); item->setData(Qt::EditRole, QVariant((itemQty*itemPrice)-itemDiscount)); //fixed on april 30 2009 00:35. item = ui_mainview.tableWidget->item(rowCount, colPrice); item->setData(Qt::EditRole, QVariant(itemPrice)); //This resizes the heigh... looks beter... ui_mainview.tableWidget->resizeRowsToContents(); if (productsHash.contains(itemCode.toULongLong())) { ProductInfo info = productsHash.value(itemCode.toULongLong()); if (info.units != uPiece) itemDoubleClicked(item);//NOTE: Pieces must be id=1 at database!!!! its a workaround. ///WARNING: March 17 2012. Im implementing a double clicking feature for adding a delegate for typing the new QTY for the clicked item. /// So, this will cause problems with this call (maybe more). } refreshTotalLabel(); ui_mainview.editItemCode->setFocus(); // BFB: editFilterbyDesc keeps the focus, if (!ui_mainview.editFilterByDesc->hasFocus()) ui_mainview.editItemCode->setFocus(); setupGridView(); if (QApplication::keyboardModifiers().testFlag(Qt::ControlModifier) == false){ ui_mainview.editItemCode->setText(""); ui_mainview.editItemCode->setCursorPosition(0); } ui_mainview.mainPanel->setCurrentIndex(pageMain); return rowCount; } void iotposView::deleteSelectedItem() { if (startingReservation || finishingReservation) { KNotification *notify = new KNotification("information", this); notify->setText(i18n("Cannot delete items from a reservation.")); QPixmap pixmap = DesktopIcon("dialog-information",32); notify->setPixmap(pixmap); notify->sendEvent(); return; } bool continueIt=false; bool reinsert = false; double qty=0; if (ui_mainview.tableWidget->currentRow()!=-1 && ui_mainview.tableWidget->selectedItems().count()>4) { if ( !Settings::lowSecurityMode() ) { if (Settings::requiereDelAuth() ) { dlgPassword->show(); dlgPassword->hide(); dlgPassword->clearLines(); if ( dlgPassword->exec() ) continueIt=true; } else continueIt=true; //if requiereDelAuth } else continueIt=true; //if no low security if (continueIt) { int row = ui_mainview.tableWidget->currentRow(); QTableWidgetItem *item = ui_mainview.tableWidget->item(row, colCode); QString codeStr = item->data(Qt::DisplayRole).toString(); if ( codeStr.toULongLong() == 0 ) { //its not a product, its a s.o. codeStr.remove(0,3); //remove the "so." string qulonglong id = codeStr.toULongLong(); if (specialOrders.contains(id)) { SpecialOrderInfo info = specialOrders.take(id); //check if is completing the order if (info.status == stReady) { //yes, its completing the order, but wants to cancel the action. //remove from listview ui_mainview.tableWidget->removeRow(row); ui_mainview.editItemCode->setFocus(); setupGridView(); if (ui_mainview.tableWidget->rowCount() == 0) ui_mainview.groupClient->setEnabled(true); refreshTotalLabel(); qDebug()<<" Removing a SO when completing the Order"; return; } if ( info.qty == 1 ) { Azahar *myDb = new Azahar; myDb->setDatabase(db); myDb->deleteSpecialOrder(id); //remove from listview ui_mainview.tableWidget->removeRow(row); QString authBy = dlgPassword->username(); if (authBy.isEmpty()) authBy = myDb->getUserName(1); //default admin. log(loggedUserId, QDate::currentDate(), QTime::currentTime(), i18n("Removing an Special Item from shopping list. Authorized by %1",authBy)); if (ui_mainview.tableWidget->rowCount() == 0) ui_mainview.groupClient->setEnabled(true); ui_mainview.editItemCode->setFocus(); setupGridView(); refreshTotalLabel(); delete myDb; return; } //more than one double iqty = info.qty-1; info.qty = iqty; double newdiscount = info.disc * info.payment * iqty; item = ui_mainview.tableWidget->item(row, colQty); item->setData(Qt::EditRole, QVariant(iqty)); item = ui_mainview.tableWidget->item(row, colDue); item->setData(Qt::EditRole, QVariant((iqty*info.payment)-newdiscount)); item = ui_mainview.tableWidget->item(row, colDisc); item->setData(Qt::EditRole, QVariant(newdiscount)); //reinsert to the hash specialOrders.insert(info.orderid,info); } if (ui_mainview.tableWidget->rowCount() == 0) ui_mainview.groupClient->setEnabled(true); ui_mainview.editItemCode->setFocus(); setupGridView(); refreshTotalLabel(); return; //to exit the method, we dont need to continue. } qulonglong code = item->data(Qt::DisplayRole).toULongLong(); ProductInfo info = productsHash.take(code); //insert it later... qty = info.qtyOnList; //this must be the same as obtaining from the table... this arrived on Dec 18 2007 //if the itemQty is more than 1, decrement it, if its 1, delete it item = ui_mainview.tableWidget->item(row, colUnits);//get item Units in strings... QString iUnitString = item->data(Qt::DisplayRole).toString(); item = ui_mainview.tableWidget->item(row, colQty); //get Qty if ((item->data(Qt::DisplayRole).canConvert(QVariant::Double))) { qty = item->data(Qt::DisplayRole).toDouble(); //NOTE: // Here, we are going to delete only items that are bigger than 1. and remove them one by one.. // or are we goint to decrement items only sold by pieces? if (qty>1 && info.units==uPiece) { qty--; item->setData(Qt::EditRole, QVariant(qty)); double price = info.price; double discountperitem = info.disc; double newdiscount = discountperitem*qty; item = ui_mainview.tableWidget->item(row, colDue); item->setData(Qt::EditRole, QVariant((qty*price)-newdiscount)); item = ui_mainview.tableWidget->item(row, colDisc); item->setData(Qt::EditRole, QVariant(newdiscount)); info.qtyOnList = qty; reinsert = true; }//if qty>1 else { //Remove from the productsHash and tableWidget... //get item code //int removed = productsHash.remove(code); productsHash.remove(code); ui_mainview.tableWidget->removeRow(row); reinsert = false; }//qty = 1... }//if canConvert if (reinsert) productsHash.insert(code, info); //we remove it with .take... Azahar *myDb = new Azahar; myDb->setDatabase(db); QString authBy = dlgPassword->username(); if (authBy.isEmpty()) authBy = myDb->getUserName(1); //default admin. log(loggedUserId, QDate::currentDate(), QTime::currentTime(), i18n("Removing an article from shopping list. Authorized by %1", authBy)); delete myDb; qDebug()<<"** REMOVING A PRODUCT [updating balance/transaction]"; updateBalance(false); updateTransaction(); }//continueIt }//there is something to delete.. if (ui_mainview.tableWidget->rowCount() == 0) ui_mainview.groupClient->setEnabled(true); refreshTotalLabel(); } void iotposView::itemDoubleClicked(QTableWidgetItem* item) { int row = item->row(); double dqty = 0.0; bool ok = false; int iqty = 0; QTableWidgetItem *i2Modify = ui_mainview.tableWidget->item(row, colCode); qulonglong code = i2Modify->data(Qt::DisplayRole).toULongLong(); if (!productsHash.contains(code)) { //its not a product, its a s.o. QString oid = i2Modify->data(Qt::DisplayRole).toString(); oid.remove(0,3); qulonglong id = oid.toULongLong(); if (specialOrders.contains(id)) { SpecialOrderInfo info = specialOrders.take(id); //check if is completing the order if (info.status == stReady) return; //is completing the order, cant modify qty. iqty = info.qty+1; info.qty = iqty; double newdiscount = info.disc * info.payment * iqty; i2Modify = ui_mainview.tableWidget->item(row, colQty); i2Modify->setData(Qt::EditRole, QVariant(iqty)); i2Modify = ui_mainview.tableWidget->item(row, colDue); i2Modify->setData(Qt::EditRole, QVariant((iqty*info.payment)-newdiscount)); i2Modify = ui_mainview.tableWidget->item(row, colDisc); i2Modify->setData(Qt::EditRole, QVariant(newdiscount)); //reinsert to the hash specialOrders.insert(info.orderid,info); } ui_mainview.editItemCode->setFocus(); setupGridView(); refreshTotalLabel(); return; //to exit the method, we dont need to continue. } ProductInfo info = productsHash.take(code); double dmaxItems = info.stockqty; QString msg = i18n("Enter the number of %1", info.unitStr); //Added on Dec 15, 2007 bool allowNegativeStock = Settings::allowNegativeStock(); //Launch a dialog to ask the new qty if (info.units == uPiece) { if (dmaxItems > 0 || allowNegativeStock) { ok = true; iqty = info.qtyOnList+1; //NOTE: Present a dialog to enter a qty or increment by one ? } } else { ///FIXME: Alert the user why is restricted to a max items! if (dmaxItems <= 0 && allowNegativeStock ) dmaxItems = 9999999; //just allow negative stock. InputDialog *dlg = new InputDialog(this, false, dialogMeasures, msg, 0.001, dmaxItems); if (dlg->exec() ) { dqty = dlg->dValue; ok=true; } delete dlg; } if (ok) { double newqty = dqty+iqty; //one must be zero //modify Qty and discount... i2Modify = ui_mainview.tableWidget->item(row, colQty); i2Modify->setData(Qt::EditRole, QVariant(newqty)); double price = info.price; double discountperitem = info.disc; double newdiscount = discountperitem*newqty; i2Modify = ui_mainview.tableWidget->item(row, colDue); i2Modify->setData(Qt::EditRole, QVariant((newqty*price)-newdiscount)); i2Modify = ui_mainview.tableWidget->item(row, colDisc); i2Modify->setData(Qt::EditRole, QVariant(newdiscount)); info.qtyOnList = newqty; setupGridView(); ui_mainview.editItemCode->setFocus(); } else { msg = i18n("<html><font color=red><b>Product not available in stock for the requested quantity.</b></font></html>"); ui_mainview.editItemCode->clearFocus(); tipCode->showTip(msg, 6000); } productsHash.insert(code, info); refreshTotalLabel(); } void iotposView::itemSearchDoubleClicked(QTableWidgetItem *item) { int row = item->row(); QTableWidgetItem *cItem = ui_mainview.tableSearch->item(row,5); //get item code: at row 5 from May 2012 qulonglong code = cItem->data(Qt::DisplayRole).toULongLong(); //qDebug()<<"Linea 981: Data at column 2:"<<cItem->data(Qt::DisplayRole).toString(); if (productsHash.contains(code)) { int pos = getItemRow(QString::number(code)); if (pos>=0) { QTableWidgetItem *thisItem = ui_mainview.tableWidget->item(pos, colCode); ProductInfo info = productsHash.value(code); if (info.units == uPiece) incrementTableItemQty(QString::number(code), 1); else itemDoubleClicked(thisItem); ///WARNING: March 17 2012. Im implementing a double clicking feature for adding a delegate for typing the new QTY for the clicked item. } } else { insertItem(QString::number(code)); } ui_mainview.mainPanel->setCurrentIndex(pageMain); } void iotposView::displayItemInfo(QTableWidgetItem* item) { int row = item->row(); qulonglong code = (ui_mainview.tableWidget->item(row, colCode))->data(Qt::DisplayRole).toULongLong(); QString desc = (ui_mainview.tableWidget->item(row, colDesc))->data(Qt::DisplayRole).toString(); double price = (ui_mainview.tableWidget->item(row, colPrice))->data(Qt::DisplayRole).toDouble(); if (productsHash.contains(code)) { ProductInfo info = productsHash.value(code); QString uLabel=info.unitStr; // Dec 15 2007 double disc = 0; if (info.disc < 0) { //price change, to higher price. price = info.price - info.disc; } else { disc = info.disc; price = info.price; } ui_mainview.stackedWidget_2->setCurrentIndex(1); ui_mainview.stackedWidget_3->setCurrentIndex(0); //ui_mainview.lblSubtotalPre->show(); // ui_mainview.lblSubtotal->show(); //ui_mainview.labelChangepre->hide(); //ui_mainview.labelChange->hide(); double discP=0.0; if (info.validDiscount) discP = info.discpercentage; QString str; QString tTotalTax= i18n("Taxes:"); QString tTax = i18n("Tax:"); QString tOTax = i18n("Other taxes:"); QString tUnits = i18n("Sold by:"); QString tPrice = i18n("Price:"); QString tDisc = i18n("Discount:"); QString tPoints = i18n("Points:"); double pWOtax = 0; if (Settings::addTax()) //added on jan 28 2010 pWOtax = info.price; else pWOtax= info.price/(1+((info.tax+info.extratax)/100)); //This is not 100% exact. double tax1m = (info.tax/100)*pWOtax; double tax2m = (info.extratax/100)*pWOtax; info.totaltax = tax1m + tax2m; QPixmap pix; pix.loadFromData(info.photo); ui_mainview.labelDetailPhoto->setPixmap(pix); str = QString("%1 (%2 %)") .arg(KGlobal::locale()->formatMoney(info.totaltax)).arg(info.tax+info.extratax); ui_mainview.labelDetailTotalTaxes->setText(QString("<html>%1 <b>%2</b></html>") .arg(tTotalTax).arg(str)); str = QString("%1 (%2 %)") .arg(KGlobal::locale()->formatMoney(tax1m)).arg(info.tax); ui_mainview.labelDetailTax1->setText(QString("<html>%1 <b>%2</b></html>") .arg(tTax).arg(str)); str = QString("%1 (%2 %)") .arg(KGlobal::locale()->formatMoney(tax2m)).arg(info.extratax); ui_mainview.labelDetailTax2->setText(QString("<html>%1 <b>%2</b></html>") .arg(tOTax).arg(str)); ui_mainview.labelDetailUnits->setText(QString("<html>%1 <b>%2</b></html>") .arg(tUnits).arg(uLabel)); ui_mainview.labelDetailDesc->setText(QString("<html><b>%1</b></html>").arg(desc)); ui_mainview.labelDetailPrice->setText(QString("<html>%1 <b>%2</b></html>") .arg(tPrice).arg(KGlobal::locale()->formatMoney(price))); ui_mainview.labelDetailDiscount->setText(QString("<html>%1 <b>%2 (%3 %)</b></html>") .arg(tDisc).arg(KGlobal::locale()->formatMoney(disc)).arg(discP)); if (info.points>0) { ui_mainview.labelDetailPoints->setText(QString("<html>%1 <b>%2</b></html>") .arg(tPoints).arg(info.points)); ui_mainview.labelDetailPoints->show(); } else ui_mainview.labelDetailPoints->hide(); } } /* TRANSACTIONS ZONE */ /*------------------*/ QString iotposView::getCurrentTransactionString() { return QString::number(currentTransaction); } qulonglong iotposView::getCurrentTransaction() { return currentTransaction; } void iotposView::createNewTransaction(TransactionType type) { //If there is an operation started, doit... if ( operationStarted ) { TransactionInfo info; info.type = type; info.amount = 0; info.date = QDate::currentDate(); info.time = QTime::currentTime(); info.paywith= 0; info.changegiven =0; info.paymethod = pCash; info.state = tNotCompleted; info.userid = loggedUserId; info.clientid = clientInfo.id; info.cardnumber ="-NA-"; info.cardauthnum="-NA-"; info.itemcount= 0; info.itemlist = ""; info.disc = 0; info.discmoney = 0; info.points = 0; info.utility = 0; //info.groups = ""; info.providerid = 1; //default one... for no.. FIXME! info.terminalnum=Settings::editTerminalNumber(); info.balanceId = currentBalanceId; info.cardType = 1; info.cardTypeStr = ""; Azahar *myDb = new Azahar; myDb->setDatabase(db); currentTransaction = myDb->insertTransaction(info); qDebug()<<"NEW TRANSACTION:"<<currentTransaction; if (currentTransaction <= 0) { KMessageBox::detailedError(this, i18n("IotPOS has encountered an error when openning database, click details to see the error details."), myDb->lastError(), i18n("Create New Transaction: Error")); } else { transactionInProgress = true; emit signalUpdateTransactionInfo(); } delete myDb; } productsHash.clear(); specialOrders.clear(); bundlesHash->clear(); } void iotposView::finishCurrentTransaction() { bool canfinish = true; completingOrder = false; //reset flag.. TicketInfo ticket; refreshTotalLabel(); QString msg; ui_mainview.mainPanel->setCurrentIndex(pageMain); if (ui_mainview.editAmount->text().isEmpty()) ui_mainview.editAmount->setText("0.0"); if (ui_mainview.checkCash->isChecked() || ui_mainview.checkOwnCredit->isChecked()) { double amnt = ui_mainview.editAmount->text().toDouble(); ///NOTE:The bug that does not accept exact amount to pay, came in recent time. It was not present some time ago. /// Maybe it is due to some system|library software update (change). qDebug()<<" amnt :"<<QString::number(amnt,'f',64); qDebug()<<" totalSum:"<<QString::number(totalSum,'f',64); //another aproach QLocale localeForPrinting; QString amntStr = localeForPrinting.toString(amnt, 'f', 2); //amount tendered QString totalStr = localeForPrinting.toString(totalSum, 'f', 2); //total qDebug()<<" Tendered Str:"<<amntStr<<" Total Str:"<<totalStr; if ( amnt < totalSum ) { canfinish = false; ui_mainview.editAmount->setFocus(); ui_mainview.editAmount->setStyleSheet("background-color: rgb(255,100,0); color:white; selection-color: white; font-weight:bold;"); //ui_mainview.editCardNumber->setStyleSheet(""); ui_mainview.editAmount->setSelection(0, ui_mainview.editAmount->text().length()); msg = i18n("<html><font color=red><b>Please fill the correct payment amount before finishing a transaction.</b></font></html>"); tipAmount->showTip(msg, 4000); ui_mainview.editAmount->setFocus(); ui_mainview.editAmount->setText(QString::number(totalSum)); ui_mainview.editAmount->selectAll(); } else if (ui_mainview.editAmount->text().length() >= 8 ) { if (ui_mainview.editAmount->text().contains(".00") || ui_mainview.editAmount->text().contains(",00")) canfinish = true; // it was not entered by the barcode reader. //To continue with that big number, the cashier needs to enter a .00 or ,00 at the end of the amnt. else { // This can be an EAN8/EAN13 barcode introduced in the amount field! // There are reports of users doing this, leading to a bad balance. msg = i18n("Please be sure to enter an appropiate amount in this field. The number seems to be a barcode entered by mistake in the amount field."); tipAmount->showTip(msg, 10000); //let stay more time than other msg. canfinish = false; ui_mainview.editAmount->setSelection(0, ui_mainview.editAmount->text().length()); //NOTE: THIS LINE OF CODE IS THE 16,000th WRITTEN LINE!!!! According to SLOCCOUNT. MCH december 25 2009. } } } else { //Remove the Creditcard boxes as no longer tenderedChanged QMessageBox::StandardButton accept; accept = QMessageBox::question(this, i18n("Credit Card Accepted?"), i18n("Please refer to EFTPOS terminal\n Has payment been accepted?"), QMessageBox::No|QMessageBox::Yes); if (accept == QMessageBox::Yes) { // If the credit card has been accepted then continue on qDebug() << "Credit card payment accepted"; canfinish = true; } else if (accept == QMessageBox::No) { // If the credit card has not been accepted then cancel the transaction. cancelCurrentTransaction(); qDebug() << "Transaction canceled due to filed credit card"; // } //check if card type is != none. qDebug()<<"CARD TYPE index:"<<ui_mainview.comboCardType->currentIndex(); if ( ui_mainview.comboCardType->currentIndex() == 0 ) { //currentIndex == 0 => Type NONE. canfinish = true; // msg = i18n("<html><font color=red><b>The Card Type must be of some valid type.</b></font></html>"); //ui_mainview.comboCardType->setFocus(); } if (!msg.isEmpty()) tipAmount->showTip(msg, 4000); } if (ui_mainview.tableWidget->rowCount() == 0) canfinish = false; if (!canStartSelling()) { canfinish=false; KMessageBox::sorry(this, i18n("Before selling, you must start operations.")); } if (ui_mainview.checkOwnCredit->isChecked() && clientInfo.id <= 1 ) { QString msgC = i18n("<html><font color=red><b>The customer for an interal credit sale must not be the default customer.</b> Please select another customer</font></html>"); canfinish = false; notifierPanel->showNotification(msgC,3000); ui_mainview.editClient->setFocus(); } if (!canfinish) return; ///WARNING:at the end of the if (canfinish){} block, there is oDiscount..= 0; is this right or not? can we safely quit here? At the beginnig of this method the oDiscount is calculated when calling refreshTotalLabel() method. if (canfinish) // Ticket #52: Allow ZERO DUE. { ui_mainview.editAmount->setStyleSheet(""); //ui_mainview.editCardNumber->setStyleSheet(""); TransactionInfo tInfo; tInfo.cardType = 1; //none PaymentType pType; double payWith = 0.0; double payTotal = 0.0; double changeGiven = 0.0; QString authnumber = ""; QString cardNum = ""; QString paidStr = "'[Not Available]'"; QStringList groupList; payTotal = totalSum; if (ui_mainview.checkCash->isChecked()) { pType = pCash; if (!ui_mainview.editAmount->text().isEmpty()) payWith = ui_mainview.editAmount->text().toDouble(); changeGiven = payWith- totalSum; } else if (ui_mainview.checkCard->isChecked()) { pType = pCard; qDebug()<<"Credit Card Selected"; payWith = payTotal; } else { //own credit pType = pOwnCredit; payWith = payTotal; changeGiven = 0; ///TODO: Any other ownCredit stuff? } tInfo.id = currentTransaction; tInfo.balanceId = currentBalanceId; tInfo.type = 0;//already on db. qDebug()<<"FinishingReservation:"<<finishingReservation<<" reservation Payment:"<<reservationPayment; if (finishingReservation) tInfo.amount = totalSum + reservationPayment; //at the transaction the REAL total must be considered (for accountability) else tInfo.amount = totalSum; //new feature from biel : Change sale date time bool printDTticket=true; if (!ui_mainview.groupSaleDate->isHidden()) { //not hidden, change date. QDateTime datetime = ui_mainview.editTransactionDate->dateTime(); tInfo.date = datetime.date(); tInfo.time = datetime.time(); ticket.datetime = datetime; if (!Settings::printChangedDateTicket()) printDTticket = false; } else { // hidden, keep current date as sale date. tInfo.date = QDate::currentDate(); tInfo.time = QTime::currentTime(); ticket.datetime = QDateTime::currentDateTime(); } tInfo.paywith= payWith; tInfo.changegiven =changeGiven; tInfo.paymethod = pType; tInfo.state = tCompleted; tInfo.userid = loggedUserId; tInfo.clientid = clientInfo.id; tInfo.cardnumber = cardNum; tInfo.cardauthnum= authnumber; tInfo.itemcount= 0;//later tInfo.itemlist = ""; //at the for.. tInfo.disc = clientInfo.discount; tInfo.discmoney = discMoney; //global variable... Now included the oDiscountMoney qDebug()<<"tInfo.disc:"<<tInfo.disc; qDebug()<<" tInfo.discmoney:"<<tInfo.discmoney; tInfo.points = buyPoints; //global variable... tInfo.utility = 0; //later tInfo.terminalnum=Settings::editTerminalNumber(); tInfo.providerid = 1; //default... at sale we dont use providers. tInfo.totalTax = totalTax; Azahar *myDb = new Azahar; myDb->setDatabase(db); //adding discounts for reservations (without affecting the sale totals, only transaction) if (finishingReservation) { //get data from reservation ReservationInfo rInfo = myDb->getReservationInfoFromTr( currentTransaction ); tInfo.disc = rInfo.discount; //discount percentage FIXME!!! tInfo.discmoney = 0; //this can cause troubles... just saving the discount percentage. } if (pType == pOwnCredit) { tInfo.state = tCompletedOwnCreditPending; ///setting pending payment status for the OwnCredit. //create the credit record CreditInfo credit = myDb->getCreditInfoForClient(clientInfo.id);//this creates a new one if no one exists for the client. qDebug()<<__FUNCTION__<<" :: Getting credit info..."; credit.total += totalSum; myDb->updateCredit(credit); //now create the credit history CreditHistoryInfo history; history.customerId = credit.clientId; history.date = tInfo.date; history.time = tInfo.time; history.amount = totalSum; //history amount + to indicate is a credit. Payments and debit deposits are -. history.saleId = currentTransaction; myDb->insertCreditHistory(history); } QStringList productIDs; productIDs.clear(); int cantidad=0; double utilidad=0; double soGTotal=0; //totals for all so. QDateTime soDeliveryDT; if (finishingReservation) { //set reservation status to rCompleted. myDb->setReservationStatus(reservationId, rCompleted); //Add the reservation details to the ticket ticket.isAReservation = true; ticket.reservationStarted = false; ticket.reservationPayment = reservationPayment; ticket.purchaseTotal = myDb->getReservationTotalAmount(reservationId); qDebug()<<"*** Finishing RESERVATION ID:"<<reservationId<< " Purchase Total:"<<ticket.purchaseTotal<< " With a Payment of:"<<reservationPayment; //add the reservation payment -- Dec 15 2011. Every payment must be registered, even the first one. The sum should be equal to the transaction total+taxes myDb->addReservationPayment(reservationId, totalSum); } else if (startingReservation) { ticket.isAReservation = true; ticket.reservationStarted = true; qDebug()<<"*** STARTING RESERVATION ID:"<<reservationId; //No deberia entrar aqui, porque al iniciar apartados, no termina transaccion. } else { ticket.isAReservation = false; ticket.reservationStarted = false; ticket.reservationId = 0; qDebug()<<" >>>>>>>>>>>>>>>>>>>>>>>>>>>>> OK no reservation <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<" ; } QHashIterator<qulonglong, ProductInfo> i(productsHash); int position=0; QList<TicketLineInfo> ticketLines; ticketLines.clear(); TransactionItemInfo tItemInfo; double pDiscounts=0; // NOTE: utilidad (profit): Also take into account client discount! after this... //Iterating products hash while (i.hasNext()) { QString iname = ""; i.next(); position++; productIDs.append(QString::number(i.key())+"/"+QString::number(i.value().qtyOnList)); if (i.value().units == uPiece) cantidad += i.value().qtyOnList; else cantidad += 1; // :) //WARNING: If changePrice to a higer price, dont expect to have accurate information on profit and other information. It would give a bigger profit. utilidad += (i.value().price - i.value().cost - i.value().disc) * i.value().qtyOnList; //FIXME: Now with REWRITTEN TOTALS CALCULATION!! WARNING with discount if (i.value().disc > 0 ) pDiscounts+= i.value().disc * i.value().qtyOnList; //decrement stock qty, increment soldunits.. CHECK FOR GROUP if (!i.value().isAGroup) myDb->decrementProductStock(i.key(), i.value().qtyOnList, QDate::currentDate() ); else { //ITS A GROUPED PRODUCT myDb->decrementGroupStock(i.key(), i.value().qtyOnList, QDate::currentDate() ); //GET NAME WITH ITS PRODUCTS iname = i.value().desc; //name with its components if (!i.value().groupElementsStr.isEmpty()) { QStringList lelem = i.value().groupElementsStr.split(","); //groupList << lelem;//to store on TransactionInfo foreach(QString ea, lelem) { if (Settings::printPackContents()) { qulonglong c = ea.section('/',0,0).toULongLong(); double q = ea.section('/',1,1).toDouble(); ProductInfo pi = myDb->getProductInfo(QString::number(c)); QString unitStr; if (pi.units == 1 ) unitStr=" "; else unitStr = pi.unitStr; iname += "\n " + QString::number(q) + " "+ unitStr +" "+ pi.desc; } } } } //qDebug()<<"NEWNAME:"<<iname; //from Biel // save transactionItem tItemInfo.transactionid = tInfo.id; tItemInfo.position = position; tItemInfo.productCode = i.key(); tItemInfo.points = i.value().points; // qtyOnList; //MCH: changed... tItemInfo.unitStr = i.value().unitStr; tItemInfo.qty = i.value().qtyOnList; tItemInfo.cost = i.value().cost; tItemInfo.price = i.value().price; tItemInfo.disc = i.value().disc*i.value().qtyOnList; tItemInfo.total = (i.value().price - i.value().disc) * i.value().qtyOnList; if (i.value().isAGroup) tItemInfo.name = iname.replace("\n", "|"); else tItemInfo.name = i.value().desc; tItemInfo.soId = ""; //no special order tItemInfo.payment = 0; //not used tItemInfo.completePayment = true; tItemInfo.isGroup = i.value().isAGroup; tItemInfo.tax = (i.value().tax + i.value().extratax); //tax percentage (15 == 15%), as it was originally planed. //NOTE: Apr 14 2011: I decided to print the tax % in product iteration in tickets. Instead of the money. // This way, i dont need to fix the tax money amount if the item has discounts or the sale has a client/ocassional discount. //tItemInfo.tax = i.value().totaltax*i.value().qtyOnList; //((i.value().tax + i.value().extratax)/100)*tItemInfo.total; myDb->insertTransactionItem(tItemInfo); //re-select the transactionItems model // KB:performance optimization // historyTicketsModel->select(); iname = iname.replace("\n", "|"); // add line to ticketLines TicketLineInfo tLineInfo; tLineInfo.qty = i.value().qtyOnList; tLineInfo.unitStr = i.value().unitStr; tLineInfo.isGroup = false; if (i.value().isAGroup) { //TO SEND GROUP INFO TO PRINTTICKET tLineInfo.geForPrint =iname; tLineInfo.completePayment = true; tLineInfo.payment = 0; tLineInfo.isGroup = true; } tLineInfo.desc = i.value().desc; //If a higer price with PriceChange feature: if (i.value().disc < 0 ) { tLineInfo.price = i.value().price - i.value().disc; qDebug()<<"* There is a higher price change:"<<tLineInfo.price; } else tLineInfo.price = i.value().price; tLineInfo.disc = i.value().disc*i.value().qtyOnList; tLineInfo.total = tItemInfo.total; tLineInfo.tax = tItemInfo.tax; //tLineInfo.geForPrint = ticketLines.append(tLineInfo); } //each product on productHash // KB:performance optimization //re-select the transactionItems model historyTicketsModel->select(); tInfo.itemcount = cantidad; // qty of products (again, at Hash) double soDiscounts = 0; QStringList ordersStr; int completePayments = 0; //Now check the Special Items (Orders) if (!specialOrders.isEmpty()) { QStringList elementsStr; foreach(SpecialOrderInfo siInfo, specialOrders) { // NOTE: here the Special Item is taken as ONE -not counting its components- but COUNT QTY of each SO. tInfo.itemcount += siInfo.qty; //specialOrders.count(); //Decrement each component stock! myDb->decrementSOStock(siInfo.orderid, siInfo.qty, QDate::currentDate()); position++; //increment the existent positions. ordersStr.append(QString::number(siInfo.orderid)+"/"+QString::number(siInfo.qty)); elementsStr.append(siInfo.groupElements); //NOTE: Here the 'utilidad' = profit. Profit is CERO at this stage for the S.O, // Its going to be calculated when the payment is done (when picking up the product) // and is going to be emited other transaction with the profit/payment. // TODO: Add this note to the manual. if (siInfo.status == stReady) { if ( siInfo.completePayment ) { //the Special Order is being completed... CALCULATE PROFIT. double discount = (siInfo.price * siInfo.disc * siInfo.qty) + lastDiscount; qDebug()<<"LAST DISCOUNT:"<<lastDiscount; utilidad += ((siInfo.price - siInfo.cost)*siInfo.qty) - discount;//FIXME: Now with REWRITTEN TOTALS CALCULATION!! WARNING with discount qDebug()<<" Profit for the SO:"<<((siInfo.price - siInfo.cost)*siInfo.qty)-discount<<"discount here:"<<(siInfo.price * siInfo.disc * siInfo.qty)<<" All Discount on the SO:"<<discount; //NOTE: Disconunts on any SO content is taken into consideration when adding to the transaction, // so the siInfo.price that comes from the SO Editor does NOT include discounts. // ALSO the price and cost is for ONE PACK. If incrementing/decrementing at iotpos or at // the SpecialOrderEditor (qty for the Order, not components), the siInfo.qty will contain this // quantity, to be multiplied by the price and cost to get the TOTAL SALE cost and price for each SO. } } if (siInfo.units == 1) cantidad += siInfo.qty; else cantidad +=1; //from Biel // save transactionItem tItemInfo.disc = 0; tItemInfo.transactionid = tInfo.id; tItemInfo.position = position; tItemInfo.productCode = 0; //are qulonlong... and they are not normal products tItemInfo.points = 0; tItemInfo.unitStr = siInfo.unitStr; tItemInfo.qty = siInfo.qty; tItemInfo.cost = siInfo.cost; tItemInfo.price = siInfo.price; tItemInfo.disc = siInfo.disc * siInfo.price * siInfo.qty; //this is the total discount soDiscounts += tItemInfo.disc; double disc2 = siInfo.disc * siInfo.payment * siInfo.qty; //this is the discount on the prepayment double taxPercentage = (myDb->getSpecialOrderAverageTax(siInfo.orderid)); double taxmoney = myDb->getSpecialOrderAverageTax(siInfo.orderid, rtMoney)*siInfo.qty; // tax per qty (still needs to be multiplied by qty) tItemInfo.total = (siInfo.price*siInfo.qty)-tItemInfo.disc; //NOTE: Apr 14 2011: I decided to print the tax % in product iteration in tickets. Instead of the money. // This way, i dont need to fix the tax money amount if the item has discounts or the sale has a client/ocassional discount. tItemInfo.tax = taxPercentage; //taxmoney; tItemInfo.name = siInfo.name; tItemInfo.soId = "so."+QString::number(siInfo.orderid); double sumTax =0; if (Settings::addTax()) sumTax=taxmoney; tItemInfo.payment = (siInfo.payment*siInfo.qty) -disc2 + sumTax; //(taxPercentage*((siInfo.payment*siInfo.qty)-disc2)); //qDebug()<<"ItemInfo taxes:"<<taxmoney; tItemInfo.completePayment = siInfo.completePayment; tItemInfo.deliveryDateTime= siInfo.deliveryDateTime; tItemInfo.isGroup = false; if (siInfo.completePayment && siInfo.status == stReady) completePayments++; myDb->insertTransactionItem(tItemInfo); //re-select the transactionItems model historyTicketsModel->select(); // add line to ticketLines TicketLineInfo tLineInfo; tLineInfo.disc = 0; tLineInfo.qty = siInfo.qty; tLineInfo.unitStr = siInfo.unitStr; tLineInfo.desc = siInfo.name; tLineInfo.price = siInfo.price; tLineInfo.disc = siInfo.disc * siInfo.price * siInfo.qty; // april 5 2005: Now SO can have discounts tLineInfo.partialDisc =disc2; tLineInfo.total = tItemInfo.total; double gtotal = tItemInfo.total + tItemInfo.tax; tLineInfo.gtotal = Settings::addTax() ? gtotal : tLineInfo.total; soGTotal += tLineInfo.gtotal; soDeliveryDT = siInfo.deliveryDateTime; // this will be the same for all the SO, so it does not matter if overwrited. tLineInfo.geForPrint = siInfo.geForPrint; tLineInfo.completePayment = siInfo.completePayment; tLineInfo.payment = tItemInfo.payment; tLineInfo.isGroup = false; tLineInfo.deliveryDateTime = siInfo.deliveryDateTime; tLineInfo.tax = tItemInfo.tax; //qDebug()<<" \n==== total:"<<tLineInfo.total<<" Payment:"<< tLineInfo.payment<<" siInfo.payment:"<<siInfo.payment //<<" pDisc:"<<disc2<<" % tax $"<<tItemInfo.tax<<" Gran Total:"<<tLineInfo.gtotal<<"\n"; ///NOTE: Testing with addTax setting and using a sample SO, there is a DIFFERENCE of 18 cents ( the client pays 18 cents less of the real price) /// (REAL PRICE = 285.18, PAID: 285 ). This is the result of the 'rounding' in multiple operations done during the process. /// The error is 0.063 % (285.18 * .00063 = .18) ticketLines.append(tLineInfo); switch (siInfo.status) { case stPending: siInfo.status = stInProgress; //some clients makes the total payment when ordering. if (siInfo.completePayment) siInfo.completedOnTrNum = tInfo.id; myDb->updateSpecialOrder(siInfo); break; case stInProgress: qDebug()<<"There is an inappropiate state (In progress) for a SO to be here."; break; case stReady: siInfo.status = stDelivered; siInfo.completedOnTrNum = tInfo.id; //siInfo.payment = siInfo.price-siInfo.payment; //the final payment is what we save on db. myDb->updateSpecialOrder(siInfo); break; case stDelivered: qDebug()<<"There is an inappropiate state (Delivered) for a SO to be here."; break; default: qDebug()<<"No state for the SO, setting as InProgress"; siInfo.status =stInProgress; myDb->updateSpecialOrder(siInfo); break; } //update special order info (when resume sale is used, deliveryDateTime is changed) myDb->updateSpecialOrder(siInfo); //update completingOrder flag completingOrder = siInfo.completePayment; //considering the last one at the end, all SO must have the same status! } //for each }// !specialOrders.isEmpty // taking into account the client discount. Applied over other products discount. // discMoney is the money discounted because of client discount. //double _taxes = 0; //if (!Settings::addTax()) _taxes = totalTax; // NOTE: If taxes included in price ( !addTax() ) the profit include tax amount. // Taxes paid to the gov. are calculated with profit.TODO:VERIFY this information! accountants knowledge fro each country needed. ///FIXME: Now with REWRITTEN TOTALS CALCULATION!! WARNING with discount utilidad = utilidad - discMoney; //The net profit == profit minus the discount (client || occasional) if ( !specialOrders.isEmpty() ) { if ( !completingOrder ) { //This means there are special orders, and if they are NOT completing, so profit must be ZERO. utilidad = 0; qDebug()<<"STARTING A SPECIAL ORDER. The Profit set to ZERO *****"; } } tInfo.utility = utilidad; //NOTE: ? - _taxes; tInfo.itemlist = productIDs.join(","); qDebug()<<"\nSALE NET PROFIT:"<< utilidad<<" discMoney:"<<discMoney<<"\n"; //special orders Str on transactionInfo tInfo.specialOrders = ordersStr.join(","); //all special orders on the hash formated as id/qty,id/qty... //update transactions myDb->updateTransaction(tInfo); //increment client points myDb->incrementClientPoints(tInfo.clientid, tInfo.points); if (drawerCreated) { //FIXME: What to di first?... add or substract?... when there is No money or there is less money than the needed for the change.. what to do? if (ui_mainview.checkCash->isChecked()) { drawer->addCash(payWith); drawer->substractCash(changeGiven); drawer->incCashTransactions(); //open drawer only if there is a printer available. if (Settings::openDrawer() && Settings::smallTicketDotMatrix() && Settings::printTicket()) drawer->open(); } else { /// OwnCredit also will be incremented in CARD transactions. No cash IN for this sales. drawer->incCardTransactions(); drawer->addCard(payWith); } drawer->insertTransactionId(getCurrentTransaction()); } else { //KMessageBox::error(this, i18n("The Drawer is not initialized, please start operation first."), i18n("Error") ); KNotification *notify = new KNotification("information", this); notify->setText(i18n("The Drawer is not initialized, please start operation first.")); QPixmap pixmap = DesktopIcon("dialog-information",32); notify->setPixmap(pixmap); notify->sendEvent(); } //update client info in the hash.... clientInfo.points += buyPoints; clientsHash.remove(QString::number(clientInfo.id)); clientsHash.insert(QString::number(clientInfo.id), clientInfo); updateClientInfo(); refreshTotalLabel(); QString realSubtotal; //if (Settings::addTax()) { //realSubtotal = KGlobal::locale()->formatMoney(subTotalSum-discMoney+soDiscounts+pDiscounts, QString(), 2); realSubtotal = KGlobal::locale()->formatMoney(subTotalSum+discMoney+soDiscounts+pDiscounts, QString(), 2); qDebug()<<"\n realSubtotal[1]\t\tsubTotalSum:" << subTotalSum << ", discMoney: " << discMoney << ", soDiscounts: " << soDiscounts << ", pDiscounts: " << pDiscounts << endl; //} //else { // realSubtotal = KGlobal::locale()->formatMoney(subTotalSum-totalTax+discMoney+soDiscounts+pDiscounts, QString(), 2); //FIXME: es +discMoney o -discMoney?? // qDebug()<<"\n realSubtotal[2]\t\tsubTotalSum:" << subTotalSum << ", totalTax: " << totalTax << ", discMoney: " << discMoney << ", soDiscounts: " << soDiscounts << ", pDiscounts: " << pDiscounts << endl; //} qDebug()<<"\n pDiscounts:"<<pDiscounts; qDebug()<<"\n >>>>>>>>> Real SUBTOTAL = "<<realSubtotal<<" subTotalSum = "<<subTotalSum<<" ADDTAXES:"<<Settings::addTax()<<" Disc:"<<discMoney; qDebug()<<"\n********** Total Taxes:"<<totalTax<<" total Discount:"<<discMoney<< " SO Discount:"<<soDiscounts<<" Prod Discounts:"<<pDiscounts; //Ticket ticket.number = currentTransaction; ticket.subTotal = realSubtotal; //This is the subtotal-taxes-discount ticket.total = payTotal; ticket.change = changeGiven; ticket.paidwith = payWith; ticket.itemcount = cantidad; ticket.cardnum = cardNum; ticket.cardAuthNum = authnumber; ticket.paidWithCard = ui_mainview.checkCard->isChecked(); ticket.clientDisc = clientInfo.discount; ticket.clientDiscMoney = discMoney; ticket.buyPoints = buyPoints; ticket.clientPoints = clientInfo.points; ticket.lines = ticketLines; ticket.clientid = clientInfo.id; ticket.hasSpecialOrders = !specialOrders.isEmpty(); if (completePayments>0) ticket.completingSpecialOrder = true; else ticket.completingSpecialOrder = false; ticket.totalTax = totalTax; ticket.soTotal = soGTotal; ticket.deliveryDT = soDeliveryDT; ticket.terminal = QString::number(tInfo.terminalnum); qDebug()<<" \n soGTotal:"<<soGTotal<<" deliveryDT:"<<soDeliveryDT<<"\n"; BasketPriceCalculationService basketPriceCalculationService; BasketPriceSummary summary = basketPriceCalculationService.calculateBasketPrice(this->productsHash, this->clientInfo, oDiscountMoney); Currency subtotal(summary.getGross()); subtotal.add(summary.getDiscountGross()); subtotal.substract(summary.getTax()); ticket.subTotal = KGlobal::locale()->formatMoney(subtotal.toDouble(), QString(), 2); ticket.totalTax = summary.getTax().toDouble(); //ticket.total = summary.getGross() ; ticket.clientDiscMoney = 0.0; qDebug() << "KB: sub and total " << ticket.subTotal << " / " << ticket.totalTax; //ptInfo.totDisc = summary.getDiscountGross().toDouble(); if (printDTticket) printTicket(ticket); else { //if not printing ticket, it means it is config to not print date changed tickets.. but this affects to the freeze/unfreeze UI, and to call startAgain(). freezeWidgets(); QTimer::singleShot(500, this, SLOT(unfreezeWidgets())); qDebug()<<"Not printing ticket..."; } //update balance qDebug()<<"FINISH TRANSACTION, UPDATING BALANCE #"<<currentBalanceId; updateBalance(false);//for sessions. transactionInProgress = false; updateModelView(); ui_mainview.editItemCode->setFocus(); setupGridView(); //Check level of cash in drawer if (drawer->getAvailableInCash() < Settings::cashMinLevel() && Settings::displayWarningOnLowCash()) { //KPassivePopup::message( i18n("Warning:"),i18n("Cash level in drawer is low."),DesktopIcon("dialog-warning", 48), this); KNotification *notify = new KNotification("information", this); notify->setText(i18n("Cash level in drawer is low.")); QPixmap pixmap = DesktopIcon("dialog-warning",32); //NOTE: This does not works notify->setPixmap(pixmap); notify->sendEvent(); } delete myDb; } if (!ui_mainview.groupSaleDate->isHidden()) ui_mainview.groupSaleDate->hide(); //finally we hide the sale date group completingOrder = false; //cleaning flag oDiscountMoney = 0; //reset discount money... the new discount type. if (loggedUserRole == roleAdmin) {/*updateGraphs();*/} //showProductsGrid(); setupGridView(); ui_mainview.labelTotalDiscountpre->hide(); ui_mainview.labelTotalDiscount->hide(); ui_mainview.stackedWidget_3->setCurrentIndex(3); ui_mainview.editItemCode->setFocus(); if (ui_mainview.rbFilterByCategory->isChecked()) { //by category ui_mainview.frameGridView->show(); } } void iotposView::printTicket(TicketInfo ticket) { if (ticket.total == 0 && !Settings::printZeroTicket()) { freezeWidgets(); KNotification *notify = new KNotification("information", this); notify->setText(i18n("The ticket was not printed because it is ZERO in the amount to pay. Just to save trees.")); QPixmap pixmap = DesktopIcon("dialog-error",32); notify->setPixmap(pixmap); notify->sendEvent(); QTimer::singleShot(2000, this, SLOT(unfreezeWidgets())); return; ///DO NOT PRINT! We are saving trees. } //TRanslateable strings: QString salesperson = i18n("Salesperson: %1", loggedUserName); QString hQty = i18n("Qty"); QString hProduct = i18n("Product"); QString hPrice = i18n("Price"); QString hDisc = i18n("Discount"); QString hTotal = i18n("Total"); QString hClientDisc = i18n("Your Personal Discount"); QString hClientBuyPoints = i18n("Your points this buy: %1", ticket.buyPoints); QString hClientPoints = i18n("Your total points: %1", ticket.clientPoints); QString hTicket = i18n("# %1", ticket.number); QString terminal = i18n("Terminal #%1", ticket.terminal); QString hPrePayment = i18n("PRE PAYMENT OF"); QString hCompletePayment = i18n("COMPLETED PAYMENT WITH"); QString hNextPaymentStr = i18n("To complete your payment"); QString hLastPaymentStr = i18n("Your pre payment"); QString hSpecialOrder = i18n("SPECIAL ORDERS"); QString hNotes = i18n("Notes:"); QString hDeliveryDT = i18n("Delivery"); QString hTax = i18n("Tax"); QString hSubtotal = i18n("Subtotal"); QString hTendered = i18n("Tendered"); //HTML Ticket QStringList ticketHtml; double tDisc = 0.0; //Ticket header ticketHtml.append(QString("<html><body><b>%1 - %2</b> [%3]<br>Ticket #%4 %5 %6<br>") .arg(Settings::editStoreName()) .arg(Settings::storeAddress()) .arg(Settings::storePhone()) .arg(ticket.number) .arg(salesperson) .arg(terminal)); //Ticket Table header ticketHtml.append(QString("<table border=0><tr><th>%1</th><th>%2</th><th>%3</th><th>%4</th><th>%5</th></tr>") .arg(hQty).arg(hProduct).arg(hPrice).arg(hDisc).arg(hTotal)); //TEXT Ticket QStringList itemsForPrint; QString line; line = QString("%1, %2").arg(Settings::editStoreName()).arg(Settings::storeAddress()); //FIXME:Check Address lenght for ticket itemsForPrint.append(line); line = QString("%1").arg(terminal); itemsForPrint.append(line); line = QString("%1 %2").arg(hTicket).arg(salesperson); itemsForPrint.append(line); line = KGlobal::locale()->formatDateTime(ticket.datetime, KLocale::LongDate); itemsForPrint.append(line); itemsForPrint.append(" "); hQty.append(" ").truncate(6); hProduct.append(" ").truncate(14); hPrice.append(" ").truncate(7); hTotal.append(" ").truncate(6); //qDebug()<< "Strings:"<< hQty;qDebug()<< ", "<< hProduct<<", "<<hPrice<<", "<<hTotal; itemsForPrint.append(hQty +" "+ hProduct +" "+ hPrice+ " "+ hTotal); itemsForPrint.append("------ -------------- ------- -------"); QLocale localeForPrinting; // needed to convert double to a string better for (int i = 0; i < ticket.lines.size(); ++i) { TicketLineInfo tLine = ticket.lines.at(i); QString idesc = tLine.desc; QString iprice = localeForPrinting.toString(tLine.price,'f',2); QString iqty = localeForPrinting.toString(tLine.qty,'f',2); if (iprice.endsWith(".00") || iprice.endsWith(",00")) { iprice.chop(3); }//we chop the trailing zeroes... if (iqty.endsWith(".00") || iqty.endsWith(",00")) { iqty.chop(3); }//we chop the trailing zeroes... iqty = iqty+" "+tLine.unitStr; QString idiscount = localeForPrinting.toString(/*tLine.qty**/tLine.disc,'f',2); bool hasDiscount = false; if (tLine.disc > 0) { hasDiscount = true; tDisc = tDisc + /*tLine.qty**/tLine.disc; } QString idue = localeForPrinting.toString(tLine.total,'f',2); if (idue.endsWith(".00") || idue.endsWith(",00")) { idue.chop(3); }//we chop the trailing zeroes... //get contents, remove the first which is the name of the SO QStringList contentsList = tLine.geForPrint.split("|"); if (!contentsList.isEmpty()) contentsList.removeFirst(); //HTML Ticket ticketHtml.append(QString("<tr><td>%1</td><td>%2</td><td>%3</td><td>%4</td><td>%5</td></tr>") .arg(iqty).arg(idesc).arg(iprice).arg(idiscount).arg(idue)); if (!tLine.geForPrint.isEmpty()) { ticketHtml.append(QString("<tr><td></td><td>%1</td><td></td><td></td><td></td></tr>").arg(contentsList.join("\n"))); if (tLine.completePayment) { if (!tLine.isGroup) ticketHtml.append(QString("<tr><td></td><td>%1</td><td></td><td></td><td></td></tr>").arg(hCompletePayment+QString::number(tLine.payment*tLine.qty))); } else { if (!tLine.isGroup) ticketHtml.append(QString("<tr><td></td><td>%1</td><td></td><td></td><td></td></tr>").arg(hPrePayment+QString::number(tLine.payment*tLine.qty))); } } //TEXT TICKET //adjusting length if (idesc.length()>14) idesc.truncate(14); //idesc = idesc.insert(19, '\n'); else { while (idesc.length()<14) idesc = idesc.insert(idesc.length(), ' '); } iqty.append(" ").truncate(6); while (iprice.length()<7) iprice = QString(" ").append(iprice); while (idue.length()<7) idue = QString(" ").append(idue); // while (iqty.length()<7) iqty = iqty.insert(iqty.length(), ' '); // while (idiscount.length()<4) idiscount = idiscount.insert(idiscount.length(), ' '); line = QString("%1 %2 %3 %4"). arg(iqty). arg(idesc). arg(iprice). arg(idue); itemsForPrint.append(line); if (!contentsList.isEmpty()) { itemsForPrint<<contentsList; if (tLine.completePayment) { if (!tLine.isGroup) itemsForPrint<<(hCompletePayment+" "+QString::number(tLine.payment/**tLine.qty*/)); } else { if (!tLine.isGroup) itemsForPrint<<(hPrePayment+" "+QString::number(tLine.payment/**tLine.qty*/)); } if (!tLine.isGroup && tLine.payment > 0) { //print the delivery date. itemsForPrint<<(hDeliveryDT+" "+KGlobal::locale()->formatDateTime(tLine.deliveryDateTime, KLocale::ShortDate)); } } if (hasDiscount) itemsForPrint.append(QString(" * %1 * -%2").arg(hDisc).arg(idiscount) ); }//for each item tDisc = tDisc + ticket.clientDiscMoney; //HTML Ticket QString harticles = i18np("%1 article.", "%1 articles.", ticket.itemcount); QString htotal = i18n("A total of"); ticketHtml.append(QString("</table><br><br><b>%1</b> %2 <b>%3</b>") .arg(harticles).arg(htotal).arg(KGlobal::locale()->formatMoney(ticket.total, QString(), 2))); ticketHtml.append(i18n("<br>Paid with %1, your change is <b>%2</b><br>", KGlobal::locale()->formatMoney(ticket.paidwith, QString(), 2), KGlobal::locale()->formatMoney(ticket.change, QString(), 2))); ticketHtml.append(Settings::editTicketMessage()); //Text Ticket itemsForPrint.append(" "); line = QString("%1 %2 %3").arg(harticles).arg(htotal).arg(KGlobal::locale()->formatMoney(ticket.total, QString(), 2)); itemsForPrint.append(line); itemsForPrint.append(" "); if (tDisc > 0) { line = i18n("You saved %1", KGlobal::locale()->formatMoney(tDisc, QString(), 2)); itemsForPrint.append(line); } if (ticket.clientDiscMoney>0) itemsForPrint.append(hClientDisc+": "+QString::number(ticket.clientDiscMoney)); if (ticket.buyPoints>0 && ticket.clientid>1) itemsForPrint.append(hClientBuyPoints); if (ticket.clientPoints>0 && ticket.clientid>1) itemsForPrint.append(hClientPoints); // itemsForPrint.append(" "); line = i18n("Paid with %1, your change is %2", KGlobal::locale()->formatMoney(ticket.paidwith, QString(), 2), KGlobal::locale()->formatMoney(ticket.change, QString(), 2)); itemsForPrint.append(line); if (ticket.paidWithCard) { ticketHtml.append(i18n("<br>Card # %1<br>Authorisation # %2",ticket.cardnum, ticket.cardAuthNum)); line = i18n("Card Number:%1 \nAuthorisation #:%2",ticket.cardnum,ticket.cardAuthNum); itemsForPrint.append(line); itemsForPrint.append(" "); } line = QString(Settings::editTicketMessage()); itemsForPrint.append(line); if (Settings::printZeroTicket()) { itemsForPrint.append(" "); itemsForPrint.append("\n"); itemsForPrint.append(" "); } ticketHtml.append("</body></html>"); //Printing... qDebug()<< itemsForPrint.join("\n"); //tDisc = tDisc + ticket.clientDiscMoney; NOTE: moved above, aug 7 2011. text ticket did not get clientDiscMoney. ///Real printing... [sendind data to print-methods] if (Settings::printTicket()) { if (Settings::smallTicketDotMatrix()) { QString printerFile=Settings::printerDevice(); if (printerFile.length() == 0) printerFile="/dev/ttyAMA0"; QString printerCodec=Settings::printerCodec(); if (Settings::printZeroTicket()) { // Send to spool file QFile fOut("/home/pi/iotpos/printing/spool"); if (fOut.open(QFile::WriteOnly | QFile::Text)) { QTextStream s(&fOut); for (int i = 0; i < itemsForPrint.size(); ++i) s << itemsForPrint.at(i) << '\n'; fOut.close(); QProcess process; process.startDetached("sudo", QStringList() << "python" << "/home/pi/iotpos/scripts/push.py"); } else { std::cerr << "error opening output file\n"; //return EXIT_FAILURE; } } else { PrintDEV::printSmallTicket(printerFile, printerCodec, itemsForPrint.join("\n")); } } else if (Settings::smallTicketCUPS() ) { // some code inspired on Daniel O'Neill code. qDebug()<<"Printing small receipt using CUPS"; PrintTicketInfo ptInfo; //NOTE: Apr 14 2011: If we print to a dot-matrix printer using CUPS, then we need to REMOVE PIXMAPS because they will print pages of strange characters. //FIXME: We need an extra option in config for this (using cups for dot-matrix printers) QPixmap logoPixmap; logoPixmap.load(Settings::storeLogo()); //foreach(TicketLineInfo li, ticket.lines) { // qDebug()<<"TicketLine.geForPrint:"<<li.geForPrint; //} Azahar *myDb = new Azahar; myDb->setDatabase(db); QString clientName = myDb->getClientInfo(ticket.clientid).name; CreditInfo crInfo = myDb->getCreditInfoForClient(ticket.clientid, false); //gets the credit info for the client, wihtout creating a new creditInfo if not exists. if (crInfo.id > 0) { //the client has credit info. ptInfo.thPoints = i18n(" %3 [ %4 ]| You got %1 points | Your accumulated is :%2 | | Your credit balance is: %5", ticket.buyPoints, ticket.clientPoints, clientName, ticket.clientid, KGlobal::locale()->formatMoney(crInfo.total, QString(), 2)); } else { ptInfo.thPoints = i18n(" %3 [ %4 ]| You got %1 points | Your accumulated is :%2 | ", ticket.buyPoints, ticket.clientPoints, clientName, ticket.clientid); } ptInfo.ticketInfo = ticket; ptInfo.storeLogo = logoPixmap; ptInfo.storeName = Settings::editStoreName(); ptInfo.storeAddr = Settings::storeAddress(); ptInfo.storePhone = Settings::storePhone(); ptInfo.ticketMsg = Settings::editTicketMessage(); ptInfo.salesPerson= loggedUserName; ptInfo.terminal = terminal; ptInfo.thPhone = i18n("Phone: "); ptInfo.thDate = KGlobal::locale()->formatDateTime(ptInfo.ticketInfo.datetime, KLocale::LongDate); ptInfo.thTicket = hTicket; ptInfo.thProduct = hProduct; ptInfo.thQty = i18n("Qty"); ptInfo.thPrice = hPrice; ptInfo.thDiscount = hDisc; ptInfo.thTotal = hTotal; ptInfo.thTotals = KGlobal::locale()->formatMoney(ptInfo.ticketInfo.total, QString(), 2); ptInfo.thArticles = i18np("%1 article.", "%1 articles.", ptInfo.ticketInfo.itemcount); ptInfo.thPaid = KGlobal::locale()->formatMoney(ptInfo.ticketInfo.paidwith, QString(), 2); ptInfo.thChange = KGlobal::locale()->formatMoney(ptInfo.ticketInfo.change, QString(), 2); ptInfo.thChangeStr= i18n("Change"); ptInfo.tDisc = KGlobal::locale()->formatMoney(-tDisc, QString(), 2); ptInfo.thCard = i18n("Card Number : %1", ticket.cardnum); ptInfo.thCardAuth = i18n("Authorization : %1", ticket.cardAuthNum); ptInfo.totDisc = tDisc; ptInfo.subtotal = ticket.subTotal; ptInfo.logoOnTop = Settings::chLogoOnTop(); //QString signM = KGlobal::locale()->formatMoney(tDisc, QString(), 2); //signM.truncate(2); //NOTE: this is only getting the sign "$"... ptInfo.paymentStrPrePayment = hPrePayment; ptInfo.paymentStrComplete = hCompletePayment; ptInfo.nextPaymentStr = hNextPaymentStr; ptInfo.lastPaymentStr = hLastPaymentStr; ptInfo.deliveryDateStr= hDeliveryDT; ptInfo.clientDiscMoney = ticket.clientDiscMoney; ptInfo.clientDiscountStr = hClientDisc; ptInfo.randomMsg = myDb->getRandomMessage(rmExcluded, rmSeason); ptInfo.taxes = KGlobal::locale()->formatMoney(ticket.totalTax, QString(), 2); ptInfo.thTax = hTax; ptInfo.thSubtotal = hSubtotal; ptInfo.thTendered = hTendered; //for reservations ptInfo.hdrReservation = i18n(" RESERVATION "); if (!ptInfo.ticketInfo.reservationStarted) ptInfo.resTotalAmountStr = i18n("Purchase Total Amount"); else ptInfo.resTotalAmountStr = i18n("Reservation Total Amount"); // BasketPriceCalculationService basketPriceCalculationService; // BasketPriceSummary summary = basketPriceCalculationService.calculateBasketPrice(this->productsHash, this->clientInfo, oDiscountMoney); // ptInfo.subtotal = summary.getGross().toDouble() + summary.getDiscountGross().toDouble(); // ptInfo.taxes = summary.getTax().toDouble(); // ptInfo.totDisc = summary.getDiscountGross().toDouble(); QPrinter printer; printer.setFullPage( true ); //This is lost when the user chooses a printer. Because the printer overrides the paper sizes. printer.setPageMargins(0,0,0,0,QPrinter::Millimeter); //TODO:Nueva impresora. printer.setPaperSize(QSizeF(72,200), QPrinter::Millimeter); //setting small ticket paper size. 72mm x 200mm //NOTE: Ojo: si se hace click en el boton "Properties" del dialogo de Imprimir, aunque se presione "cancel", el "PAGE" se pone como 204mm //NOTE: El calculo del tamano de fuente no es correcta para papeles mayores a 72mm de anchos. QString pName = printer.printerName(); //default printer name QPrintDialog printDialog( &printer ); printDialog.setWindowTitle(i18n("Print Receipt -- Press ESC to export to PDF to your home/iotpos-printing/ folder")); ptInfo.totDisc = discMoney; ptInfo.tDisc = KGlobal::locale()->formatMoney(-discMoney, QString(), 2); if ( printDialog.exec() ) { //this overrides what the user chooses if he does change sizes and margins. printer.setPageMargins(0,0,0,0,QPrinter::Millimeter); //printer.setPaperSize(QSizeF(72,200), QPrinter::Millimeter); //setting small ticket paper size. 72mm x 200mm //TODO: Set Copies: printer.setCopyCount(2); //NOTE:Introduced in Qt 4.7 --WARNING-- See also setCollateCopies() PrintCUPS::printSmallTicket(ptInfo, printer); //export anyway QString fn = QString("%1/iotpos-printing/").arg(QDir::homePath()); QDir dir; if (!dir.exists(fn)) dir.mkdir(fn); fn = fn+QString("ticket-%1__%2.pdf").arg(ticket.number).arg(ticket.datetime.date().toString("dd-MMM-yy")); qDebug()<<fn; printer.setOutputFileName(fn); printer.setPageMargins(0,0,0,0,QPrinter::Millimeter); PrintCUPS::printSmallTicket(ptInfo, printer); } else { //NOTE: This is a proposition: // If the dialog is accepted (ok), then we print what the user choosed. Else, we print to a file (PDF). // The user can press ENTER when dialog appearing if the desired printer is the default (or the only). qDebug()<<"User cancelled printer dialog. We export ticket to a file."; QString fn = QString("%1/iotpos-printing/").arg(QDir::homePath()); QDir dir; if (!dir.exists(fn)) dir.mkdir(fn); fn = fn+QString("ticket-%1__%2.pdf").arg(ticket.number).arg(ticket.datetime.date().toString("dd-MMM-yy")); qDebug()<<fn; printer.setOutputFileName(fn); printer.setPageMargins(0,0,0,0,QPrinter::Millimeter); printer.setPaperSize(QSizeF(72,200), QPrinter::Millimeter); //setting small ticket paper size. 72mm x 200mm PrintCUPS::printSmallTicket(ptInfo, printer); } delete myDb; } else { qDebug()<<"Printing big receipt using CUPS"; PrintTicketInfo ptInfo; QPixmap logoPixmap; logoPixmap.load(Settings::storeLogo()); Azahar *myDb = new Azahar; myDb->setDatabase(db); QString clientName = myDb->getClientInfo(ticket.clientid).name; ptInfo.ticketInfo = ticket; ptInfo.storeLogo = logoPixmap; ptInfo.storeName = Settings::editStoreName(); ptInfo.storeAddr = Settings::storeAddress(); ptInfo.storePhone = Settings::storePhone(); ptInfo.ticketMsg = Settings::editTicketMessage(); ptInfo.salesPerson= loggedUserName; ptInfo.terminal = terminal; ptInfo.thPhone = i18n("Phone: "); ptInfo.thDate = KGlobal::locale()->formatDateTime(ptInfo.ticketInfo.datetime, KLocale::LongDate); ptInfo.thTicket = hTicket; ptInfo.thProduct = hProduct; ptInfo.thQty = i18n("Qty"); ptInfo.thPrice = hPrice; ptInfo.thDiscount = hDisc; ptInfo.thTotal = hTotal; ptInfo.thTotals = KGlobal::locale()->formatMoney(ptInfo.ticketInfo.total, QString(), 2); ptInfo.thPoints = i18n(" %3 [ %4 ]| You got %1 points | Your accumulated is :%2 | ", ticket.buyPoints, ticket.clientPoints, clientName, ticket.clientid); ptInfo.thArticles = i18np("%1 article.", "%1 articles.", ptInfo.ticketInfo.itemcount); ptInfo.thPaid = ""; //i18n("Paid with %1, your change is %2", KGlobal::locale()->formatMoney(ptInfo.ticketInfo.paidwith, QString(), 2),KGlobal::locale()->formatMoney(ptInfo.ticketInfo.change, QString(), 2) ); ptInfo.tDisc = KGlobal::locale()->formatMoney(-tDisc, QString(), 2); ptInfo.subtotal = ticket.subTotal; ptInfo.totDisc = tDisc; ptInfo.logoOnTop = Settings::chLogoOnTop(); ptInfo.clientDiscMoney = ticket.clientDiscMoney; ptInfo.clientDiscountStr = hClientDisc; ptInfo.randomMsg = myDb->getRandomMessage(rmExcluded, rmSeason); QPrinter printer; printer.setFullPage( true ); QPrintDialog printDialog( &printer ); printDialog.setWindowTitle(i18n("Print Receipt")); if ( printDialog.exec() ) { PrintCUPS::printBigTicket(ptInfo, printer); } delete myDb; }//bigTicket //now if so.. print it if (Settings::printSO() && ticket.hasSpecialOrders && !ticket.completingSpecialOrder){ qDebug()<<"Printing small receipt for SPECIAL ORDERS using CUPS"; PrintTicketInfo ptInfo; ptInfo.ticketInfo = ticket; ptInfo.storeName = hSpecialOrder; //user for header ptInfo.salesPerson= loggedUserName; ptInfo.terminal = terminal; ptInfo.thDate = KGlobal::locale()->formatDateTime(ptInfo.ticketInfo.datetime, KLocale::LongDate); ptInfo.thTicket = hTicket; ptInfo.thProduct = hProduct; ptInfo.thQty = i18n("Qty"); ptInfo.thPrice = hPrice; ptInfo.thTotal = hTotal; ptInfo.thTotals = KGlobal::locale()->formatMoney(ptInfo.ticketInfo.total, QString(), 2); QString signM = KGlobal::locale()->formatMoney(tDisc, QString(), 2); signM.truncate(2); //this gets the $ only... ptInfo.paymentStrPrePayment = hPrePayment + signM; ptInfo.paymentStrComplete = hCompletePayment + signM; ptInfo.nextPaymentStr = hNextPaymentStr; ptInfo.lastPaymentStr = hLastPaymentStr; ptInfo.deliveryDateStr = hDeliveryDT; QPrinter printer; printer.setFullPage( true ); QPrintDialog printDialog( &printer ); printDialog.setWindowTitle(i18n("Print Special Order Instructions ")); if ( printDialog.exec() ) { PrintCUPS::printSmallSOTicket(ptInfo, printer); } }//soticket } //printTicket freezeWidgets(); if (Settings::showDialogOnPrinting()) { TicketPopup *popup = new TicketPopup(ticketHtml.join(" "), DesktopIcon("iotpos-printer", 32), Settings::ticketTime()*1000); connect (popup, SIGNAL(onTicketPopupClose()), this, SLOT(unfreezeWidgets()) ); QApplication::beep(); popup->popup(); } else { QTimer::singleShot(Settings::ticketTime()*1000, this, SLOT(unfreezeWidgets())); //ticket time used to allow the cashier to see the change to give the user... is configurable. } } void iotposView::freezeWidgets() { emit signalDisableUI(); } void iotposView::unfreezeWidgets() { emit signalEnableUI(); startAgain(); ui_mainview.editItemCode->setFocus(); ui_mainview.stackedWidget_3->setCurrentIndex(1); ui_mainview.listView->scrollToTop(); } void iotposView::startAgain() { qDebug()<<"startAgain(): New Transaction"; productsHash.clear(); specialOrders.clear(); bundlesHash->clear(); setupClients(); //clear the clientInfo (sets the default client info) clearUsedWidgets(); buyPoints =0; discMoney=0; globalDiscount = 0; refreshTotalLabel(); createNewTransaction(tSell); reservationPayment = 0; //reservationPayment is for reservations only! availabilityDoesNotMatters = false; // Only for reservations for now! doNotAddMoreItems = false; finishingReservation = false; startingReservation = false; reservationId = 0; //qDebug()<<" doNotAddMoreItems = false. FinishingReservation = false."; refreshTotalLabel(); //NOTE: when createNewTRansaction is executed, and we are exiting application, the requested transaction create in not completed.. due to the way it is implemented in qtsql. This is a good thing for me because i dont want to create a new transaction when we are exiting iotpos. Thats why the message "QSqlDatabasePrivate::removeDatabase: connection 'qt_sql_default_connection' is still in use, all queries will cease to work." appears on log (std output) when exiting iotpos. This method is called from corteDeCaja which is called from cancelByExit() method which is called by iotpos class on exit-query. //NOTE: But if we want to save something when exiting iotpos -sending the query at the end- we must check for it to complete. In this case, this is the last query sent... but later with more code aded, could be a danger not to check for this things. } void iotposView::cancelCurrentTransaction() { bool continueIt = false; if ( !Settings::lowSecurityMode() ) { if (Settings::requiereDelAuth() ) { dlgPassword->show(); dlgPassword->hide(); dlgPassword->clearLines(); if ( dlgPassword->exec() ) continueIt=true; } else continueIt=true; //if requiereDelAuth } else continueIt=true; //if no low security if (continueIt) {cancelTransaction(getCurrentTransaction());} //ui_mainview.labelDetailPoints->show(); ui_mainview.labelTotalDiscountpre->hide(); ui_mainview.labelTotalDiscount->hide(); setupGridView(); ui_mainview.mainPanel->setCurrentIndex(0); ui_mainview.editItemCode->setFocus(); ui_mainview.stackedWidget_3->setCurrentIndex(1); ui_mainview.listView->scrollToTop(); } void iotposView::preCancelCurrentTransaction() { if (ui_mainview.tableWidget->rowCount()==0 ) { //empty transaction productsHash.clear(); specialOrders.clear(); bundlesHash->clear(); setupClients(); //clear the clientInfo (sets the default client info) clearUsedWidgets(); buyPoints =0; discMoney=0; globalDiscount = 0; refreshTotalLabel(); qDebug()<<"** Cancelling an empty transaction [updating transaction]"; updateTransaction(); ///Next two lines were deleted to do not increment transactions number. reuse it. //if (Settings::deleteEmptyCancelledTransactions()) deleteCurrentTransaction(); //else cancelCurrentTransaction(); } else { cancelCurrentTransaction(); //updateTransaction(); //updateBalance(false); } //if change sale date is in progress (but cancelled), hide it. if (!ui_mainview.groupSaleDate->isHidden()) { ui_mainview.groupSaleDate->hide(); } ui_mainview.labelTotalDiscountpre->hide(); ui_mainview.labelTotalDiscount->hide(); setupGridView(); ui_mainview.editItemCode->setFocus(); ui_mainview.stackedWidget_3->setCurrentIndex(1); ui_mainview.listView->scrollToTop(); } void iotposView::deleteCurrentTransaction() { Azahar *myDb = new Azahar; myDb->setDatabase(db); if (myDb->deleteTransaction(getCurrentTransaction())) { transactionInProgress=false; createNewTransaction(tSell); } else { KMessageBox::detailedError(this, i18n("IotPOS has encountered an error when querying the database, click details to see the error details."), myDb->lastError(), i18n("Delete Transaction: Error")); } delete myDb; } //NOTE: This substracts points given to the client, restore stockqty, register a cashout for the money return. All if it applies. void iotposView::cancelTransaction(qulonglong transactionNumber) { bool enoughCashAvailable=false; bool transToCancelIsInProgress=false; bool transCompleted=false; Azahar *myDb = new Azahar; myDb->setDatabase(db); //get amount to return TransactionInfo tinfo = myDb->getTransactionInfo(transactionNumber); if (tinfo.state == tCancelled && tinfo.id >0) transCompleted = true; if (getCurrentTransaction() == transactionNumber) { ///this transaction is not saved yet (more than the initial data when transaction is created) //UPDATE: Now each time a product is inserted or screen locked, transaction and balance is saved. if (finishingReservation) { postponeReservation(); startAgain(); // productsHash.clear(); // specialOrders.clear(); // setupClients(); //clear the clientInfo (sets the default client info) // clearUsedWidgets(); // buyPoints =0; // discMoney=0; // finishingReservation = false; // startingReservation = false; // transactionInProgress= false; // doNotAddMoreItems = false; // createNewTransaction(tSell); // refreshTotalLabel(); return; } else { transToCancelIsInProgress = true; clearUsedWidgets(); refreshTotalLabel(); } } else { ///this transaction is saved (amount,products,points...) clearUsedWidgets(); refreshTotalLabel(); if (drawer->getAvailableInCash() > tinfo.amount && tinfo.id>0){ // == or >= or > ?? to dont let empty the drawer enoughCashAvailable = true; } } //Mark as cancelled if possible //Check if payment was with cash. //FIXME: Allow card payments to be cancelled!!! DIC 2009 if (tinfo.paymethod != 1 ) { KNotification *notify = new KNotification("information", this); notify->setText(i18n("The ticket cannot be cancelled because it was paid with a credit/debit card.")); QPixmap pixmap = DesktopIcon("dialog-error",32); notify->setPixmap(pixmap); notify->sendEvent(); return; } if (enoughCashAvailable || transToCancelIsInProgress) { qDebug()<<" ok, trans is in progress or cash is enough"; if (myDb->cancelTransaction(transactionNumber, transToCancelIsInProgress)) { QString authBy = dlgPassword->username(); if (authBy.isEmpty()) authBy = myDb->getUserName(1); //default admin. log(loggedUserId, QDate::currentDate(), QTime::currentTime(), i18n("Cancelling transaction #%1. Authorized by %2",transactionNumber,authBy)); qDebug()<<"Cancelling ticket was ok"; if (transCompleted) { //if was completed, then return the money... if (tinfo.paymethod == 1 ) {//1 is cash drawer->substractCash(tinfo.amount); if (Settings::openDrawer() && Settings::smallTicketDotMatrix() && Settings::printTicket()) drawer->open(); } //Inform to the user. KNotification *notify = new KNotification("information", this); notify->setText(i18n("The ticket was sucessfully cancelled.")); QPixmap pixmap = DesktopIcon("dialog-error",32); notify->setPixmap(pixmap); notify->sendEvent(); } transactionInProgress = false; //reset createNewTransaction(tSell); } else { //myDB->cancelTransaction() returned some error... qDebug()<<"Not cancelled!"; if (!transToCancelIsInProgress) { KNotification *notify = new KNotification("information", this); notify->setText(i18n("Error cancelling ticket: %1",myDb->lastError())); QPixmap pixmap = DesktopIcon("dialog-error",32); notify->setPixmap(pixmap); notify->sendEvent(); } else { //Reuse the transaction instead of creating a new one. qDebug()<<"Transaction to cancel is in progress. Clearing all to reuse transaction number..."; productsHash.clear(); specialOrders.clear(); bundlesHash->clear(); setupClients(); //clear the clientInfo (sets the default client info) clearUsedWidgets(); buyPoints =0; discMoney=0; globalDiscount = 0; refreshTotalLabel(); qDebug()<<"** Cancelling current transaction [updating transaction]"; updateTransaction(); } } } else { //not cash available in drawer to return money to the client OR transaction id does not exists QString msg; if (tinfo.id > 0) msg = i18n("There is not enough cash available in the drawer."); else msg = i18n("Ticket to cancel does not exists!"); KNotification *notify = new KNotification("information", this); notify->setText(msg); QPixmap pixmap = DesktopIcon("dialog-error",32); notify->setPixmap(pixmap); notify->sendEvent(); } delete myDb; setupGridView(); ui_mainview.editItemCode->setFocus(); } void iotposView::startOperation(const QString &adminUser) { qDebug()<<"Starting operations..."; operationStarted = false; bool ok=false; double qty=0.0; //TODO:preset as the money on the drawer on the last user. InputDialog *dlg = new InputDialog(this, false, dialogMoney, i18n("Enter the amount of money to deposit in the drawer")); dlg->setEnabled(true); if (dlg->exec() ) { qty = dlg->dValue; if (qty >= 0) ok = true; //allow no deposit... } delete dlg; if (ok) { if (!drawerCreated) { drawer = new Gaveta(); drawer->setPrinterDevice(Settings::printerDevice()); drawerCreated = true; } //NOTE: What about CUPS printers? Some of them can be configured to open drawer when printing. if (Settings::openDrawer() && Settings::smallTicketDotMatrix() && Settings::printTicket()) drawer->open(); // Set drawer amount. drawer->reset(); drawer->setStartDateTime(QDateTime::currentDateTime()); drawer->setAvailableInCash(qty); //this also sets the available in card amount drawer->setInitialAmount(qty); operationStarted = true; createNewTransaction(tSell); emit signalStartedOperation(); log(loggedUserId, QDate::currentDate(), QTime::currentTime(), i18n("Operation Started by %1 at terminal %2", adminUser, Settings::editTerminalNumber())); } else { qDebug()<<"Starting Operations cancelled..."; emit signalEnableStartOperationAction(); emit signalNoLoggedUser(); } //SESSIONS DEC 28 2009 if (currentBalanceId <= 0 ) { qDebug()<<"StartOperations::INSERT_BALANCE"; insertBalance(); //this updates the currentBalanceId } else { qDebug()<<"StartOperations::UPDATE_BALANCE [should not occurr, balanceId="<<currentBalanceId<<"]"; updateBalance(false); } ui_mainview.editItemCode->setFocus(); setupGridView(); } //this method is for iotpos.cpp's action connect for button, since button's trigger(bool) will cause to ask = trigger's var. void iotposView::_slotDoStartOperation() { //simply call the other... slotDoStartOperation(true); } void iotposView::slotDoStartOperation(const bool &ask) { //NOTE: For security reasons, we must ask for admin's password. //But, can we be more flexible -for one person store- and do not ask for password in low security mode // is ask is true we ask for auth, else we dont because it was previously asked for (calling method from corteDeCaja) //qDebug()<<"bool ask = "<<ask; qDebug()<<"doStartOperations.."; if (!operationStarted) { bool doit = false; if (Settings::lowSecurityMode() || !ask) { doit = true; } else { do { dlgPassword->show(); dlgPassword->clearLines(); dlgPassword->hide(); doit = dlgPassword->exec(); } while (!doit); }//else lowsecurity QString adminU; if (dlgPassword->username().isEmpty()) { Azahar *myDb = new Azahar; myDb->setDatabase(db); adminU = myDb->getUserName(1);//default admin. delete myDb; } if (doit) startOperation(adminU); } } /* REPORTS ZONE */ /*--------------*/ void iotposView::doCorteDeCaja() { qDebug()<<"logged user:"<<loggedUser; //This is called only from the UI (via Button or shortcut) -- request by the user. //We force a login, login forces a corteDeCaja if needed. login(); } void iotposView::corteDeCaja() { //Balance: Where there are no transactions, we dont need to doit. // Also consider the cash in the drawer. // Also, when doing a Balance, we need to force login. qDebug()<<"Transactions Count:"<<drawer->getTransactionsCount()<<" Cash in drawer:"<<drawer->getAvailableInCash(); bool yes=false; if (drawer->getTransactionsCount()>0 || drawer->getAvailableInCash()>0) yes=true; if (!yes) { // KNotification *notify = new KNotification("information", this); // notify->setText(i18n("There are no transactions to inform or cash in the drawer.")); // QPixmap pixmap = DesktopIcon("dialog-information",32); // notify->setPixmap(pixmap); // if (!loggedUser.isEmpty()) // notify->sendEvent(); //Things to do even if balance is not needed. operationStarted = false; currentBalanceId = 0; startAgain(); return; } bool doit = false; //ASK for security if no lowSecurityMode. if (Settings::lowSecurityMode()) { doit = true; } else { dlgPassword->show(); dlgPassword->clearLines(); dlgPassword->hide(); doit = dlgPassword->exec(); }//else lowsecurity if (doit) { qDebug()<<"Doing Balance.."; preCancelCurrentTransaction(); QStringList lines; QStringList linesHTML; QString line; QString dId; QString dAmount; QString dHour; QString dMinute; QString dPaidWith; PrintBalanceInfo pbInfo; updateBalance(true); //now it is finished. pbInfo.thBalanceId = i18n("Balance Id:%1", currentBalanceId); //NOTE: saveBalance was replaced by updateBalance(currentBalanceId) // Create lines to print and/or show on dialog... //----------Translated strings-------------------- QString strTitle = i18n("%1 at Terminal # %2", loggedUserName, Settings::editTerminalNumber()); QString strInitAmount = i18n("Initial Amount deposited:"); QString strInitAmountH= i18n("Deposit"); QString strInH = i18n("In"); QString strOutH = i18n("Out"); QString strInDrawerH = i18n("In Drawer"); QString strTitlePre = i18n("Drawer Balance"); QString strTitleTrans = i18n("Transactions Details"); QString strTitleTransH = i18n("Transactions"); QString strId = i18n("Id"); QString strTimeH = i18n("Time"); QString strAmount = i18n("Amount"); QString strPaidWith = i18n("Paid"); QString strPayMethodH = i18n("Method"); pbInfo.reservationNote = i18n("When Completing Reservations, the Amount may be grater than Paid (amount) because of the reservation payment."); QPixmap logoPixmap; logoPixmap.load(Settings::storeLogo()); pbInfo.storeName = Settings::editStoreName(); pbInfo.storeAddr = Settings::storeAddress(); pbInfo.storeLogo = logoPixmap; pbInfo.thTitle = strTitle; pbInfo.thDeposit = strInitAmountH; pbInfo.thIn = strInH; pbInfo.thOut = strOutH; pbInfo.thInDrawer = strInDrawerH; pbInfo.thTitleDetails = strTitleTrans; pbInfo.thTrId = strId; pbInfo.thTrTime = strTimeH; pbInfo.thTrAmount = strAmount; pbInfo.thTrPaidW = strPaidWith; pbInfo.thTrPayMethod=strPayMethodH; pbInfo.startDate = i18n("Start: %1",KGlobal::locale()->formatDateTime(drawer->getStartDateTime(), KLocale::LongDate)); pbInfo.endDate = i18n("End : %1",KGlobal::locale()->formatDateTime(QDateTime::currentDateTime(), KLocale::LongDate)); //Qty's pbInfo.initAmount = KGlobal::locale()->formatMoney(drawer->getInitialAmount(), QString(), 2); pbInfo.inAmount = KGlobal::locale()->formatMoney(drawer->getInAmount(), QString(), 2); pbInfo.outAmount = KGlobal::locale()->formatMoney(drawer->getOutAmount(), QString(), 2); pbInfo.cashAvailable=KGlobal::locale()->formatMoney(drawer->getAvailableInCash(), QString(), 2); pbInfo.logoOnTop = Settings::chLogoOnTop(); pbInfo.thTitleCFDetails = i18n("Cash flow Details"); pbInfo.thCFType = i18n("Type"); pbInfo.thCFReason = i18n("Reason"); pbInfo.thCFDate = i18n("Time"); pbInfo.notCashNote = i18n("This payment was not paid in cash."); //TODO: Hacer el dialogo de balance mejor, con un look uniforme a los demas dialogos. // Incluso insertar imagenes en el html del dialogo. //HTML line = QString("<html><body><h3>%1</h3>").arg(strTitle); linesHTML.append(line); line = QString("<center><table border=1 cellpadding=5><tr><th colspan=4>%9</th></tr><tr><th>%1</th><th>%2</th><th>%3</th><th>%4</th></tr><tr><td>%5</td><td>%6</td><td>%7</td><td>%8</td></tr></table></ceter><br>") .arg(strInitAmountH) .arg(strInH) .arg(strOutH) .arg(strInDrawerH) .arg(KGlobal::locale()->formatMoney(drawer->getInitialAmount(), QString(), 2)) .arg(KGlobal::locale()->formatMoney(drawer->getInAmount(), QString(), 2)) .arg(KGlobal::locale()->formatMoney(drawer->getOutAmount(), QString(), 2)) .arg(KGlobal::locale()->formatMoney(drawer->getAvailableInCash(), QString(), 2)) .arg(strTitlePre); linesHTML.append(line); line = QString("<table border=1 cellpadding=5><tr><th colspan=5>%1</th></tr><tr><th>%2</th><th>%3</th><th>%4</th><th>%5</th><th>%6</th></tr>") .arg(strTitleTransH) .arg(strId) .arg(strTimeH) .arg(strAmount) .arg(strPaidWith) .arg(strPayMethodH); linesHTML.append(line); //TXT lines.append(strTitle); line = QString(KGlobal::locale()->formatDateTime(QDateTime::currentDateTime(), KLocale::LongDate)); lines.append(line); lines.append("----------------------------------------"); line = QString("%1 %2").arg(strInitAmount).arg(KGlobal::locale()->formatMoney(drawer->getInitialAmount(), QString(), 2)); lines.append(line); line = QString("%1 :%2, %3 :%4") .arg(strInH) .arg(KGlobal::locale()->formatMoney(drawer->getInAmount(), QString(), 2)) .arg(strOutH) .arg(KGlobal::locale()->formatMoney(drawer->getOutAmount(), QString(), 2)); lines.append(line); line = QString(" %1 %2").arg(KGlobal::locale()->formatMoney(drawer->getAvailableInCash(), QString(), 2)).arg(strInDrawerH); lines.append(line); //Now, add a transactions report per user and for today. //At this point, drawer must be initialized and valid. line = QString("----------%1----------").arg(strTitleTrans); lines.append(line); line = QString("%1 %2 %3").arg(strId).arg(strAmount).arg(strPaidWith); lines.append(line); lines.append("---------- ---------- ----------"); lines.append(line); QList<qulonglong> transactionsByUser = drawer->getTransactionIds(); QStringList trList; qDebug()<<"# of transactions:"<<transactionsByUser.count(); //This gets all transactions ids done since last corteDeCaja. Azahar *myDb = new Azahar; myDb->setDatabase(db); for (int i = 0; i < transactionsByUser.size(); ++i) { qDebug()<<"i="<<i<<" tr # "<<transactionsByUser.at(i); qulonglong idNum = transactionsByUser.at(i); TransactionInfo info; info = myDb->getTransactionInfo(idNum); QString dPayMethod; //check if its completed and not cancelled FIXME: OwnCredit transactions? if (info.state != tCompleted ) { if (info.state != tCompletedOwnCreditPending ) { //Print the ownCredit Completed but not paid sales. Any other not print... qDebug()<<"Excluding from balance a transaction marked as state:"<<info.state; continue; } } dId = QString::number(info.id); dAmount = QString::number(info.amount); dHour = info.time.toString("hh"); dMinute = info.time.toString("mm"); dPaidWith = QString::number(info.paywith); QString tmp = QString("%1|%2|%3|%4") .arg(dId) .arg(dHour+":"+dMinute) .arg(KGlobal::locale()->formatMoney(info.amount, QString(), 2)) .arg(KGlobal::locale()->formatMoney(info.paywith, QString(), 2)); while (dId.length()<10) dId = dId.insert(dId.length(), ' '); while (dAmount.length()<14) dAmount = dAmount.insert(dAmount.length(), ' '); while ((dHour+dMinute).length()<6) dMinute = dMinute.insert(dMinute.length(), ' '); while (dPaidWith.length()<10) dPaidWith = dPaidWith.insert(dPaidWith.length(), ' '); //NOTE: Apr 14 2011: We want to save space on the tickets (receipt printers) and for this we will remove the 'CASH' // and other strings like that. Instead we will use an asterisk to indicate when a payment is not made in CASH. if (info.paymethod != pCash) dPayMethod = " **"; //dPayMethod = myDb->getPayTypeStr(info.paymethod);//using payType methods line = QString("%1 %2 %3") .arg(dId) //.arg(dHour) //.arg(dMinute) .arg(dAmount) //.arg(dPaidWith); .arg(dPayMethod); lines.append(line); line = QString("<tr><td>%1</td><td>%2:%3</td><td>%4</td><td>%5</td><td>%6</td></tr>") .arg(dId) .arg(dHour) .arg(dMinute) .arg(dAmount) .arg(dPaidWith) .arg(dPayMethod); linesHTML.append(line); tmp += "|"+dPayMethod; trList.append( tmp ); } pbInfo.trList = trList; //get CashOut list and its info... QStringList cfList; cfList.clear(); QList<CashFlowInfo> cashflowInfoList = myDb->getCashFlowInfoList( drawer->getCashflowIds() ); foreach(CashFlowInfo cfInfo, cashflowInfoList) { QString amountF = KGlobal::locale()->formatMoney(cfInfo.amount); //QDateTime dateTime; dateTime.setDate(cfInfo.date); dateTime.setTime(cfInfo.time); QString dateF = KGlobal::locale()->formatTime(cfInfo.time); QString typeSign; /*cfInfo.typeStr*/ if (cfInfo.type == ctCashIn || cfInfo.type == ctCashInReservation || cfInfo.type == ctCashInCreditPayment || cfInfo.type == ctCashInDebit) typeSign = "+"; else //TODO: IN THE FUTURE REVIEW THIS CODE, IF ADDING MORE CASH IN/OUT CASES. typeSign = "-"; QString data = QString::number(cfInfo.id) + "|" + typeSign + "|" + cfInfo.reason + "|" + amountF + "|" + dateF; cfList.append(data); } pbInfo.cfList = cfList; if (Settings::printZeroTicket()) { lines.append(" "); lines.append("\n"); lines.append(" "); } line = QString("</table></body></html>"); linesHTML.append(line); if (Settings::smallTicketDotMatrix()) { //print it on the /dev/lpXX... send lines to print showBalance(linesHTML); if (Settings::printBalances()) printBalance(lines); } else if (Settings::printBalances()) { //print it on cups... send pbInfo instead QPrinter printer; printer.setFullPage( true ); QPrintDialog printDialog( &printer ); printDialog.setWindowTitle(i18n("Print Balance")); if ( printDialog.exec() ) { printer.setPageMargins(0,0,0,0,QPrinter::Millimeter); //TODO:Nueva impresora. printer.setPaperSize(QSizeF(72,200), QPrinter::Millimeter); //setting small ticket paper size. 72mm x 200mm //NOTE: Ojo: si se hace click en el boton "Properties" del dialogo de Imprimir, aunque se presione "cancel", el "PAGE" se pone como 204mm //NOTE: El calculo del tamano de fuente no es correcta para papeles mayores a 72mm de anchos. //TODO: Set Copies: printer.setCopyCount(2); //NOTE:Introduced in Qt 4.7 --WARNING-- See also setCollateCopies() PrintCUPS::printSmallBalance(pbInfo, printer); } else { //NOTE: This is a proposition: // If the dialog is accepted (ok), then we print what the user choosed. Else, we print to a file (PDF). // The user can press ENTER when dialog appearing if the desired printer is the default (or the only). qDebug()<<"User cancelled printer dialog. We export ticket to a file."; QString fn = QString("%1/iotpos-printing/").arg(QDir::homePath()); QDir dir; if (!dir.exists(fn)) dir.mkdir(fn); fn = fn+QString("balance-%1__%2.pdf").arg(currentBalanceId).arg(QDateTime::currentDateTime().toString("dd-MMM-yy")); qDebug()<<fn; printer.setOutputFileName(fn); printer.setPageMargins(0,0,0,0,QPrinter::Millimeter); printer.setPaperSize(QSizeF(72,200), QPrinter::Millimeter); //setting small ticket paper size. 72mm x 200mm PrintCUPS::printSmallBalance(pbInfo, printer); } } ///NOTE: Really startoperation at this moment? why not wait user request it? Dec 23 2009 /// slotDoStartOperation(false); //for sessions, clear currentBalanceId currentBalanceId = 0; //this will make at startOperations to create a new one. operationStarted = false; delete myDb; } //if doit } void iotposView::endOfDay() { bool doit = false; //ASK for security if no lowSecurityMode. if (Settings::lowSecurityMode()) { doit = true; } else { dlgPassword->show(); dlgPassword->clearLines(); dlgPassword->hide(); doit = dlgPassword->exec(); }//else lowsecurity if (doit) { Azahar *myDb = new Azahar; myDb->setDatabase(db); QString authBy = dlgPassword->username(); if (authBy.isEmpty()) authBy = myDb->getUserName(1); //default admin. log(loggedUserId, QDate::currentDate(), QTime::currentTime(), i18n("End of Day report printed by %1 at terminal %2 on %3",authBy,Settings::editTerminalNumber(),QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm"))); // Get every transaction from all day, calculate sales, profit, and profit margin (%). From the same terminal qDebug()<<" [******* End of Day Report ******* ]"; AmountAndProfitInfo amountProfit; PrintEndOfDayInfo pdInfo; QList<TransactionInfo> transactionsList; QPixmap logoPixmap; logoPixmap.load(Settings::storeLogo()); amountProfit = myDb->getDaySalesAndProfit(Settings::editTerminalNumber()); transactionsList = myDb->getDayTransactions(Settings::editTerminalNumber()); pdInfo.storeName = Settings::editStoreName(); pdInfo.storeAddr = Settings::storeAddress(); pdInfo.storeLogo = logoPixmap; pdInfo.thTitle = i18n("End of day report"); pdInfo.thTicket = i18n("Id"); pdInfo.salesPerson = loggedUserName; pdInfo.terminal = i18n("at terminal # %1",Settings::editTerminalNumber()); pdInfo.thDate = KGlobal::locale()->formatDateTime(QDateTime::currentDateTime(), KLocale::LongDate); pdInfo.thTime = i18n("Time"); pdInfo.thAmount = i18n("Amount"); pdInfo.thProfit = i18n("Profit"); pdInfo.thPayMethod = i18n("Method"); pdInfo.thTotalTaxes= i18n("Total taxes collected for this terminal: "); pdInfo.logoOnTop = Settings::chLogoOnTop(); pdInfo.thTotalSales = KGlobal::locale()->formatMoney(amountProfit.amount, QString(), 2); pdInfo.thTotalProfit = KGlobal::locale()->formatMoney(amountProfit.profit, QString(), 2); QStringList lines; lines.append(pdInfo.thTitle); lines.append(pdInfo.thDate); lines.append(loggedUserName+pdInfo.terminal); lines.append(pdInfo.thTicket+" "+pdInfo.thTime+ pdInfo.thAmount+" "+pdInfo.thProfit+" "+pdInfo.thPayMethod); //lines.append(); //each transaction... double tTaxes = 0; for (int i = 0; i < transactionsList.size(); ++i) { QLocale localeForPrinting; // needed to convert double to a string better TransactionInfo info = transactionsList.at(i); //qDebug()<<" ========== transactions on end of day: i="<<i<<" ID:"<<info.id<<" amount:"<<info.amount<<" profit:"<<info.utility; QString tid = QString::number(info.id); QString hour = info.time.toString("hh:mm"); QString amount = localeForPrinting.toString(info.amount,'f',2); QString profit = localeForPrinting.toString(info.utility, 'f', 2); QString payMethod; payMethod = myDb->getPayTypeStr(info.paymethod);//using payType methods QString line = tid +"|"+ hour +"|"+ amount +"|"+ profit +"|"+ payMethod; pdInfo.trLines.append(line); lines.append(tid+" "+hour+" "+ amount+" "+profit+" "+payMethod); tTaxes += info.totalTax; qDebug()<<"total sale:"<<info.amount<<" taxes this sale:"<<info.totalTax<<" accumulated taxes:"<<tTaxes; } //for each item lines.append(i18n("Total Sales : %1",pdInfo.thTotalSales)); lines.append(i18n("Total Profit: %1",pdInfo.thTotalProfit)); //NOTE: this the best place to launch the backup process QString fn = QString("/media/pi/iotpos/iotpos-backup/");//Backups to an USB named "iotpos" mount at /media/pi QDir dir; if (!dir.exists(fn)) dir.mkdir(fn); fn = fn+QString("iotpos-db--backup--%1.sql").arg(QDateTime::currentDateTime().toString("dd-MMM-yyyy__hh.mm.AP")); qDebug()<<"BACKUP DATABASE at " << fn; QStringList params; QString pswd = "-p" + Settings::editDBPassword(); QString usr = "-u" + Settings::editDBUsername(); QString hst = "-h" + Settings::editDBServer(); QString dnm = Settings::editDBName(); QString fnm = "-r" + fn; params << hst << usr << pswd << fnm << dnm; QProcess mysqldump; mysqldump.start("mysqldump", params); mysqldump.waitForFinished(); QProcess process; process.startDetached("/bin/sh", QStringList()<< "/home/pi/iotpos/scripts/dropbox.sh"); if (Settings::printZeroTicket()) { lines.append(" "); lines.append("\n"); lines.append(" "); } //add taxes amount pdInfo.thTotalTaxes += KGlobal::locale()->formatMoney(tTaxes, QString(), 2); if (Settings::smallTicketDotMatrix()) { QString printerFile=Settings::printerDevice(); if (printerFile.length() == 0) printerFile="/dev/ttyAMA0"; QString printerCodec=Settings::printerCodec(); qDebug()<<"[Printing report on "<<printerFile<<"]"; qDebug()<<lines.join("\n"); //PrintDEV::printSmallBalance(printerFile, printerCodec, lines.join("\n")); // Writte spool and send mail of end of day report if (Settings::printZeroTicket()) { QFile fOut("/home/pi/iotpos/printing/spool"); if (fOut.open(QFile::WriteOnly | QFile::Text)) { QTextStream s(&fOut); for (int i = 0; i < lines.size(); ++i) s << lines.at(i) << '\n'; fOut.close(); QProcess process; process.startDetached("sudo", QStringList() << "python" << "/home/pi/iotpos/scripts/push.py"); process.startDetached("/bin/sh", QStringList()<< "/home/pi/iotpos/scripts/corteMail.sh"); } else { std::cerr << "error opening output file\n"; //return EXIT_FAILURE; } } else { PrintDEV::printSmallBalance(printerFile, printerCodec, lines.join("\n")); } } else if (Settings::smallTicketCUPS()) { qDebug()<<"[Printing report on CUPS small size]"; QPrinter printer; printer.setFullPage( true ); QPrintDialog printDialog( &printer ); printDialog.setWindowTitle(i18n("Print end of day report")); if ( printDialog.exec() ) { PrintCUPS::printSmallEndOfDay(pdInfo, printer); } else { //NOTE: This is a proposition: // If the dialog is accepted (ok), then we print what the user choosed. Else, we print to a file (PDF). // The user can press ENTER when dialog appearing if the desired printer is the default (or the only). qDebug()<<"User cancelled printer dialog. We export ticket to a file."; QString fn = QString("%1/iotpos-printing/").arg(QDir::homePath()); QDir dir; if (!dir.exists(fn)) dir.mkdir(fn); fn = fn+QString("endOfDay__%1.pdf").arg(QDateTime::currentDateTime().toString("dd-MMM-yy")); qDebug()<<fn; printer.setOutputFileName(fn); printer.setPageMargins(0,0,0,0,QPrinter::Millimeter); printer.setPaperSize(QSizeF(72,200), QPrinter::Millimeter); //setting small ticket paper size. 72mm x 200mm PrintCUPS::printSmallEndOfDay(pdInfo, printer); } } else { //big printer qDebug()<<"[Printing report on CUPS big size]"; QPrinter printer; printer.setFullPage( true ); QPrintDialog printDialog( &printer ); printDialog.setWindowTitle(i18n("Print end of day report")); if ( printDialog.exec() ) { PrintCUPS::printBigEndOfDay(pdInfo, printer); } } delete myDb; } } void iotposView::showBalance(QStringList lines) { if (Settings::showDialogOnPrinting()) { BalanceDialog *popup = new BalanceDialog(lines.join("\n")); popup->show(); popup->hide(); int result = popup->exec(); if (result) { //qDebug()<<"exec=true"; } } } void iotposView::printBalance(QStringList lines) { //Balances are print on small tickets. Getting the selected printed from config. if (Settings::printBalances()) { if (Settings::smallTicketDotMatrix()) { QString printerFile=Settings::printerDevice(); if (printerFile.length() == 0) printerFile="/dev/ttyAMA0"; QString printerCodec=Settings::printerCodec(); qDebug()<<"[Printing balance on "<<printerFile<<"]"; //PrintDEV::printSmallBalance(printerFile, printerCodec, lines.join("\n")); if (Settings::printZeroTicket()) { QFile fOut("/home/pi/iotpos/printing/spool"); if (fOut.open(QFile::WriteOnly | QFile::Text)) { QTextStream s(&fOut); for (int i = 0; i < lines.size(); ++i) s << lines.at(i) << '\n'; fOut.close(); QProcess process; process.startDetached("sudo", QStringList() << "python" << "/home/pi/iotpos/scripts/push.py"); if (Settings::openDrawer()) drawer->open(); } else { std::cerr << "error opening output file\n"; //return EXIT_FAILURE; } } // DOT-MATRIX PRINTER on /dev/lpX else { PrintDEV::printSmallBalance(printerFile, printerCodec, lines.join("\n")); if (Settings::openDrawer()) drawer->open(); } } } } /* MODEL Zone */ void iotposView::setupModel() { if (!db.isOpen()) { connectToDb(); } else { //workaround for a stupid crash: when re-connecting after Config, on setTable crashes. //Crashes without debug information. if (productsModel->tableName() != "products") productsModel->setTable("products"); productsModel->setEditStrategy(QSqlTableModel::OnRowChange); ui_mainview.listView->setModel(productsModel); ui_mainview.listView->setResizeMode(QListView::Adjust); ui_mainview.listView->setModelColumn(productsModel->fieldIndex("photo")); ui_mainview.listView->setViewMode(QListView::IconMode); ui_mainview.listView->setGridSize(QSize(128,128)); ui_mainview.listView->setEditTriggers(QAbstractItemView::NoEditTriggers); ui_mainview.listView->setMouseTracking(true); //for the tooltip ProductDelegate *delegate = new ProductDelegate(ui_mainview.listView); ui_mainview.listView->setItemDelegate(delegate); productsModel->select(); //Categories popuplist populateCategoriesHash(); ui_mainview.comboFilterByCategory->clear(); QHashIterator<QString, int> item(categoriesHash); while (item.hasNext()) { item.next(); ui_mainview.comboFilterByCategory->addItem(item.key()); //qDebug()<<"iterando por el hash en el item:"<<item.key()<<"/"<<item.value(); } populateCardTypes(); ui_mainview.comboFilterByCategory->setCurrentIndex(0); connect(ui_mainview.comboFilterByCategory,SIGNAL(currentIndexChanged(int)), this, SLOT( setFilter()) ); connect(ui_mainview.editFilterByDesc,SIGNAL(returnPressed()), this, SLOT( setFilter()) ); connect(ui_mainview.rbFilterByDesc, SIGNAL(toggled(bool)), this, SLOT( setFilter()) ); connect(ui_mainview.rbFilterByCategory, SIGNAL(toggled(bool)), this, SLOT( setFilter()) ); setFilter(); } setupClientsModel(); } void iotposView::setupClientsModel() { if (!db.isOpen()) { connectToDb(); } else { clientsModel->setQuery(""); //assign the completer. QCompleter *completer = new QCompleter(this); completer->setModel(clientsModel); completer->setCaseSensitivity(Qt::CaseInsensitive); //Show all possible results, because completer only works with prefix. The filter is done modifying the model completer->setCompletionMode(QCompleter::UnfilteredPopupCompletion); ui_mainview.editClientIdForCredit->setCompleter(completer); connect(ui_mainview.editClientIdForCredit,SIGNAL(textEdited(const QString)), this, SLOT( modifyClientsFilterModel()) ); ui_mainview.editClient->setCompleter(completer); //the same completer for the client edit. connect(ui_mainview.editClient,SIGNAL(textEdited(const QString)), this, SLOT( modifyClientsFilterModelB()) ); } } void iotposView::modifyClientsFilterModel() { if (ui_mainview.editClientIdForCredit->text().length() > 1){ QString search=ui_mainview.editClientIdForCredit->text(); //clientsModel->setQuery(QString("SELECT code,name FROM clients WHERE code REGEXP '%1' OR name REGEXP '%1'").arg(search)); clientsModel->setQuery(QString("SELECT concat(code, ' -- ', name) as codename,code,name FROM clients WHERE code REGEXP '%1' OR name REGEXP '%1'").arg(search)); }else{ clientsModel->setQuery(""); } } void iotposView::modifyClientsFilterModelB() { if (ui_mainview.editClient->text().length() > 1){ QString search=ui_mainview.editClient->text(); clientsModel->setQuery(QString("SELECT concat(code, ' -- ', name) as codename,code,name FROM clients WHERE code REGEXP '%1' OR name REGEXP '%1'").arg(search)); }else{ clientsModel->setQuery(""); } } void iotposView::populateCategoriesHash() { Azahar * myDb = new Azahar; myDb->setDatabase(db); categoriesHash = myDb->getCategoriesHash(); delete myDb; } void iotposView::listViewOnMouseMove(const QModelIndex & index) { //NOTE: Problem: here the data on the view does not change. This is because we do not // update this view's data, we modify directly the data at database until we sell a product. // and until that moment we can update this view. // UPDATE: We have at productsHash the property qtyOnList, we can use such qty to display available qty. // But if we are working on a network (multiple POS). It will not be true the information. QString tprice = i18n("Price: "); QString tstock = i18n("Available: "); QString tdisc = i18n("Discount:"); //TODO: Only include if valid until now... QString tcategory = i18n("Category:"); QString tmoreAv = i18n("in stock"); QString tmoreAv2= i18n("in your shopping cart, Total Available"); //getting data from model... const QAbstractItemModel *model = index.model(); int row = index.row(); QModelIndex indx = model->index(row, 1); QString desc = model->data(indx, Qt::DisplayRole).toString(); indx = model->index(row, 2); double price = model->data(indx, Qt::DisplayRole).toDouble(); indx = model->index(row, 3); double stockqty = model->data(indx, Qt::DisplayRole).toDouble(); indx = model->index(row, 0); QString code = model->data(indx, Qt::DisplayRole).toString(); ProductInfo pInfo; bool onList=false; if (productsHash.contains(code.toULongLong())) { pInfo = productsHash.value(code.toULongLong()); onList = true; } QString line1 = QString("<p><b><i>%1</i></b><br>").arg(desc); QString line2 = QString("<b>%1</b>%2<br>").arg(tprice).arg(KGlobal::locale()->formatMoney(price)); QString line3; if (onList) line3 = QString("<b>%1</b> %2 %5 %6, %3 %7: %4<br></p>").arg(tstock).arg(stockqty).arg(pInfo.qtyOnList).arg(stockqty - pInfo.qtyOnList).arg(pInfo.unitStr).arg(tmoreAv).arg(tmoreAv2); else line3 = QString("<b>%1</b> %2 %3 %4<br></p>").arg(tstock).arg(stockqty).arg(pInfo.unitStr).arg(tmoreAv); QString text = line1+line2+line3; ui_mainview.listView->setToolTip(text); } void iotposView::listViewOnClick(const QModelIndex & index) { //getting data from model... const QAbstractItemModel *model = index.model(); int row = index.row(); QModelIndex indx = model->index(row, 0); QString code = model->data(indx, Qt::DisplayRole).toString(); insertItem(code); } //This is done at the end of each transaction... void iotposView::updateModelView() { //Submit and select causes a flick and costs some milliseconds productsModel->submitAll(); productsModel->select(); } void iotposView::showProductsGrid(bool show) { if (show || Settings::showGrid()) { ui_mainview.frameGridView->show(); } else { ui_mainview.frameGridView->hide(); } } void iotposView::hideProductsGrid() { ui_mainview.frameGridView->hide(); } void iotposView::showPriceChecker() { PriceChecker *priceDlg = new PriceChecker(this); priceDlg->setDb(db); priceDlg->show(); } void iotposView::setFilter() { //NOTE: This is a QT BUG. // If filter by description is selected and the text is empty, and later is re-filtered // then NO pictures are shown; even if is refiltered again. QRegExp regexp = QRegExp(ui_mainview.editFilterByDesc->text()); if (ui_mainview.rbFilterByDesc->isChecked()) { setupGridView(); ui_mainview.editItemCode->setFocus();//by description if (!regexp.isValid()) ui_mainview.editFilterByDesc->setText(""); if (ui_mainview.editFilterByDesc->text()=="*" || ui_mainview.editFilterByDesc->text()=="") productsModel->setFilter("products.isARawProduct=false"); //productsModel->setFilter("products.isARawProduct=false and (products.datelastsold > ADDDATE(sysdate( ), INTERVAL -31 DAY )) ORDER BY products.datelastsold DESC "); } else { if (ui_mainview.rbFilterByCategory->isChecked()) { //by category ui_mainview.frameGridView->show(); //Find catId for the text on the combobox. int catId=-1; QString catText = ui_mainview.comboFilterByCategory->currentText(); if (categoriesHash.contains(catText)) { catId = categoriesHash.value(catText); } productsModel->setFilter(QString("products.isARawProduct=false and products.category=%1").arg(catId)); } } productsModel->select(); } void iotposView::setupDB() { qDebug()<<"Setting up database..."; if (db.isOpen()) db.close(); //QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8")); //db = QSqlDatabase::addDatabase("QMYSQL"); db.setHostName(Settings::editDBServer()); db.setDatabaseName(Settings::editDBName()); db.setUserName(Settings::editDBUsername()); db.setPassword(Settings::editDBPassword()); connectToDb(); ///NOTE: set tableWidget delegate, and set its db. Here because we need a configured db. SaleQtyDelegate *qtyD = new SaleQtyDelegate(); qtyD->setDb(db); ui_mainview.tableWidget->setItemDelegate( qtyD ); } void iotposView::connectToDb() { if (!db.open()) { db.open(); //try to open connection qDebug()<<"(1/connectToDb) Trying to open connection to database.."; } if (!db.isOpen()) { db.open(); //try to open connection again... qDebug()<<"(2/connectToDb) Trying to open connection to database.."; } if (!db.isOpen()) { qDebug()<<"(3/connectToDb) Configuring.."; emit signalShowDbConfig(); } else { //finally, when connection stablished, setup all models. if (!modelsCreated) { //Create models... productsModel = new QSqlTableModel(); historyTicketsModel = new QSqlRelationalTableModel(); clientsModel = new QSqlQueryModel(); modelsCreated = true; } setupModel(); setupHistoryTicketsModel(); setupClients(); //pass db to login/pass dialogs dlgLogin->setDb(db); dlgPassword->setDb(db); bundlesHash->setDb(db); //checking if is the first run. Azahar *myDb = new Azahar; myDb->setDatabase(db); if (myDb->getConfigFirstRun()) syncSettingsOnDb(); delete myDb; } } void iotposView::setupClients() { qDebug()<<"Setting up clients..."; ClientInfo info; QString mainClient; clientsHash.clear(); ui_mainview.lblClientDetails->clear(); Azahar *myDb = new Azahar; myDb->setDatabase(db); clientsHash = myDb->getClientsHash(); mainClient = myDb->getMainClient(); //Set by default the 'general' client. clientInfo = clientsHash.value(mainClient); updateClientInfo(); refreshTotalLabel(); delete myDb; } void iotposView::clientChanged() { if ( !specialOrders.isEmpty() ) { // There are special orders, from now, we cannot change client ui_mainview.editClient->clear(); updateClientInfo(); refreshTotalLabel(); return; } QString newClientCode = ui_mainview.editClient->text(); //CODE Azahar *myDb = new Azahar; myDb->setDatabase(db); QString newClientName = myDb->getClientInfo(newClientCode).name; delete myDb; qDebug()<<"Client info changed by user."; if (clientsHash.contains(newClientName)) { clientInfo = clientsHash.value(newClientName); updateClientInfo(); refreshTotalLabel(); ui_mainview.editItemCode->setFocus(); setupGridView(); } } void iotposView::updateClientInfo() { QString dStr; BasketPriceCalculationService basketPriceCalculationService; BasketPriceSummary summary = basketPriceCalculationService.calculateBasketPrice(this->productsHash, this->clientInfo, oDiscountMoney); double discMoney = summary.getDiscountGross().toDouble(); //(clientInfo.discount/100)*totalSumWODisc; dStr = i18n("Discount: <b>%1%</b> [<b>%2</b>]",clientInfo.discount, KGlobal::locale()->formatMoney(discMoney)); QString pStr = i18n("<i>%1</i> points", clientInfo.points); if (clientInfo.points <= 0) pStr = ""; //QPixmap pix; //What about using a QTextEditor, and embed the photo inside? still uses space. //pix.loadFromData(clientInfo.photo); //ui_mainview.lblClientPhoto->setPixmap(pix); Azahar *myDb = new Azahar; myDb->setDatabase(db); //NOTE:maybe its better to add creditInfo to clientInfo, and from azahar::getClientInfo() get the creditInfoForClient. Need more code review at azahar. QString creditStr; CreditInfo credit = myDb->getCreditInfoForClient(clientInfo.id, false);//do not create new credit if not found. if (credit.id > 0 && credit.total != 0 ) creditStr = i18n("Credit Total: <i>%1</i>", KGlobal::locale()->formatMoney(credit.total)); else creditStr = ""; //The format is: CLIENT-NAME (Client-Code) <br>Credit <br>Discount<br>Points. ui_mainview.lblClientDetails->setText(QString("<b>%1</b> (<i>%2</i>)<br>%3<br>%4<br>%5").arg(clientInfo.name).arg(clientInfo.code).arg(creditStr).arg(dStr).arg(pStr)); delete myDb; qDebug()<<"Updating customer info..."; } void iotposView::setHistoryFilter() { historyTicketsModel->setFilter(QString("date <= STR_TO_DATE('%1', '%d/%m/%Y')"). arg(ui_mainview.editTicketDatePicker->date().toString("dd/MM/yyyy"))); historyTicketsModel->setSort(historyTicketsModel->fieldIndex("id"),Qt::DescendingOrder); //change this when implemented headers click } void iotposView::setupHistoryTicketsModel() { //qDebug()<<"Db name:"<<db.databaseName()<<", Tables:"<<db.tables(); if (historyTicketsModel->tableName().isEmpty()) { if (!db.isOpen()) db.open(); historyTicketsModel->setTable("v_transactions"); historyTicketsModel->setRelation(historyTicketsModel->fieldIndex("clientid"), QSqlRelation("clients", "id", "name")); historyTicketsModel->setRelation(historyTicketsModel->fieldIndex("userid"), QSqlRelation("users", "id", "username")); historyTicketsModel->setHeaderData(historyTicketsModel->fieldIndex("id"), Qt::Horizontal, i18n("Tr")); historyTicketsModel->setHeaderData(historyTicketsModel->fieldIndex("clientid"), Qt::Horizontal, i18n("Customer")); historyTicketsModel->setHeaderData(historyTicketsModel->fieldIndex("datetime"), Qt::Horizontal, i18n("Date")); historyTicketsModel->setHeaderData(historyTicketsModel->fieldIndex("userid"), Qt::Horizontal, i18n("User")); historyTicketsModel->setHeaderData(historyTicketsModel->fieldIndex("itemcount"), Qt::Horizontal, i18n("Items")); historyTicketsModel->setHeaderData(historyTicketsModel->fieldIndex("amount"), Qt::Horizontal, i18n("Total")); historyTicketsModel->setHeaderData(historyTicketsModel->fieldIndex("disc"), Qt::Horizontal, i18n("Discount")); ui_mainview.ticketView->setModel(historyTicketsModel); ui_mainview.ticketView->setColumnHidden(historyTicketsModel->fieldIndex("date"), true); ui_mainview.ticketView->setSelectionMode(QAbstractItemView::SingleSelection); ui_mainview.ticketView->setSelectionBehavior(QAbstractItemView::SelectRows); ui_mainview.ticketView->setEditTriggers(QAbstractItemView::NoEditTriggers); ui_mainview.ticketView->resizeColumnsToContents(); ui_mainview.ticketView->setCurrentIndex(historyTicketsModel->index(0, 0)); historyTicketsModel->setSort(historyTicketsModel->fieldIndex("id"),Qt::DescendingOrder); historyTicketsModel->select(); } setHistoryFilter(); } void iotposView::setupTicketView() { if (historyTicketsModel->tableName().isEmpty()) setupHistoryTicketsModel(); historyTicketsModel->setSort(historyTicketsModel->fieldIndex("id"),Qt::DescendingOrder); historyTicketsModel->select(); QSize tableSize = ui_mainview.ticketView->size(); int portion = tableSize.width()/7; ui_mainview.ticketView->horizontalHeader()->setResizeMode(QHeaderView::Interactive); ui_mainview.ticketView->horizontalHeader()->resizeSection(historyTicketsModel->fieldIndex("id"), portion); ui_mainview.ticketView->horizontalHeader()->resizeSection(historyTicketsModel->fieldIndex("name"), portion); ui_mainview.ticketView->horizontalHeader()->resizeSection(historyTicketsModel->fieldIndex("datetime"), portion); ui_mainview.ticketView->horizontalHeader()->resizeSection(historyTicketsModel->fieldIndex("username"), portion); ui_mainview.ticketView->horizontalHeader()->resizeSection(historyTicketsModel->fieldIndex("itemcount"), portion); ui_mainview.ticketView->horizontalHeader()->resizeSection(historyTicketsModel->fieldIndex("amount"), portion); ui_mainview.ticketView->horizontalHeader()->resizeSection(historyTicketsModel->fieldIndex("disc"), portion); } void iotposView::itemHIDoubleClicked(const QModelIndex &index){ if (db.isOpen()) { //getting data from model... const QAbstractItemModel *model = index.model(); int row = index.row(); QModelIndex indx = model->index(row, 1); // id = columna 1 qulonglong transactionId = model->data(indx, Qt::DisplayRole).toULongLong(); printTicketFromTransaction(transactionId); //return to selling tab ui_mainview.mainPanel->setCurrentIndex(pageMain); } } void iotposView::printSelTicket() { QModelIndex index = ui_mainview.ticketView->currentIndex(); if (historyTicketsModel->tableName().isEmpty()) setupHistoryTicketsModel(); if (index == historyTicketsModel->index(-1,-1) ) { KMessageBox::information(this, i18n("Please select a ticket to print."), i18n("Cannot print ticket")); } else { qulonglong id = historyTicketsModel->record(index.row()).value("id").toULongLong(); //ASK for security if no lowSecurityMode. bool doit = false; if (Settings::lowSecurityMode()) { doit = true; } else { dlgPassword->show(); dlgPassword->clearLines(); dlgPassword->hide(); doit = dlgPassword->exec(); }//else lowsecurity if (doit) printTicketFromTransaction(id); else { //show a notification. qDebug()<<"No administrator password supplied for reprint ticket"; KNotification *notify = new KNotification("information", this); notify->setText(i18n("Reprint ticket cancelled.")); QPixmap pixmap = DesktopIcon("dialog-error",32); notify->setPixmap(pixmap); notify->sendEvent(); } } //return to selling tab ui_mainview.mainPanel->setCurrentIndex(pageMain); } void iotposView::printTicketFromTransaction(qulonglong transactionNumber) { QList<TicketLineInfo> ticketLines; TicketInfo ticket; ticketLines.clear(); ticket.hasSpecialOrders = false; ticket.completingSpecialOrder = false; if (!db.isOpen()) db.open(); Azahar *myDb = new Azahar; myDb->setDatabase(db); TransactionInfo trInfo = myDb->getTransactionInfo(transactionNumber); QList<TransactionItemInfo> pListItems = myDb->getTransactionItems(transactionNumber); double itemsDiscount=0; double soGTotal = 0; QDateTime soDeliveryDT; //NOTE: Fixing printing reservations that does not exists. ReservationInfo rInfo = myDb->getReservationInfoFromTr(transactionNumber); //qDebug()<<"ReservationId:"<<rInfo.id<<" TrNum:"<<transactionNumber<<" rInfo.transaction_id"<<rInfo.transaction_id; if (rInfo.transaction_id != trInfo.id) { //its not true! ticket.reservationId = 0; ticket.isAReservation = false; } else { ticket.reservationId = rInfo.id; ticket.isAReservation = true; if ( rInfo.status == rCompleted ) //NOTE: This is not saved in the rInfo, but only completed reservations can be re-printed. ticket.reservationStarted = false; else ticket.reservationStarted = true; ticket.reservationPayment = rInfo.payment; ticket.purchaseTotal = rInfo.total; } //end fixing... for (int i = 0; i < pListItems.size(); ++i) { TransactionItemInfo trItem = pListItems.at(i); // add line to ticketLines TicketLineInfo tLineInfo; tLineInfo.qty = trItem.qty; tLineInfo.unitStr = trItem.unitStr; tLineInfo.desc = trItem.name; tLineInfo.price = trItem.price; tLineInfo.disc = trItem.disc; tLineInfo.total = trItem.total; tLineInfo.payment = trItem.payment; tLineInfo.completePayment = trItem.completePayment; tLineInfo.isGroup = trItem.isGroup; tLineInfo.deliveryDateTime = trItem.deliveryDateTime; tLineInfo.tax = trItem.tax; itemsDiscount += tLineInfo.disc; double gtotal = trItem.total + trItem.tax; tLineInfo.gtotal = Settings::addTax() ? gtotal : tLineInfo.total; soGTotal += tLineInfo.gtotal; soDeliveryDT = trItem.deliveryDateTime; // this will be the same for all the SO, so it does not matter if overwrited. qDebug()<<"\n*** item discount:"<<tLineInfo.disc<<" total itemsDiscount:"<<itemsDiscount<<"\n"; qDebug()<<"\n*** soGTotal:"<<soGTotal<<" deliveryDT:"<<soDeliveryDT<<"\n"; QString newName; newName = trItem.soId; qulonglong sorderid = newName.remove(0,3).toULongLong(); QString soNotes = myDb->getSONotes(sorderid); soNotes = soNotes.replace("\n", "| "); if (sorderid > 0) { ticket.hasSpecialOrders = true; ticket.completingSpecialOrder = false; //we are re-printing... QList<ProductInfo> pList = myDb->getSpecialOrderProductsList(sorderid); newName = ""; foreach(ProductInfo info, pList ) { QString unitStr; if (info.units == 1 ) unitStr=" "; else unitStr = info.unitStr; newName += "| " + QString::number(info.qtyOnList) + " "+ unitStr +" "+ info.desc; } tLineInfo.geForPrint = trItem.name+newName+"| |"+i18n("Notes:")+soNotes+" | "; } else tLineInfo.geForPrint = ""; //qDebug()<<"isGROUP:"<<trItem.isGroup; if (trItem.isGroup) { tLineInfo.geForPrint = trItem.name; QString n = trItem.name.section('|',0,0); trItem.name = n; tLineInfo.desc = trItem.name; } ticketLines.append(tLineInfo); } //Ticket QDateTime dt; dt.setDate(trInfo.date); dt.setTime(trInfo.time); ticket.clientid = trInfo.clientid; ticket.datetime = dt; ticket.number = transactionNumber; ticket.total = trInfo.amount; ticket.change = trInfo.changegiven; ticket.paidwith = trInfo.paywith; ticket.itemcount = trInfo.itemcount; if (!trInfo.cardnumber.isEmpty()) ticket.cardnum = trInfo.cardnumber.replace(0,15,"***************"); //FIXED: Only save last 4 digits else ticket.cardnum = ""; ticket.cardAuthNum = trInfo.cardauthnum; ticket.paidWithCard = (trInfo.paymethod == 2) ? true:false; ticket.clientDisc = trInfo.disc; ticket.clientDiscMoney = trInfo.discmoney; ticket.buyPoints = trInfo.points; ticket.clientPoints = myDb->getClientInfo(ticket.clientid).points; ticket.lines = ticketLines; ticket.terminal = QString::number(trInfo.terminalnum); ticket.totalTax = trInfo.totalTax; double subtotal = ticket.total + itemsDiscount + trInfo.discmoney; // - trInfo.totaltax; if (Settings::addTax()) subtotal = subtotal; else subtotal = subtotal - ticket.totalTax; QString realSubtotal = KGlobal::locale()->formatMoney(subtotal, QString(), 2); qDebug()<<"\n*** Ticket tax:"<<trInfo.totalTax<<" itemsDiscount:"<<itemsDiscount<<"client Discount:"<<trInfo.discmoney<<" ticket total:"<<ticket.total<<" SUBTOTAL:"<<subtotal<<" AddTax:"<<Settings::addTax()<<" \n"; ticket.subTotal = realSubtotal; if (ticket.hasSpecialOrders) ticket.deliveryDT = soDeliveryDT; ticket.soTotal = soGTotal; printTicket(ticket); delete myDb; } void iotposView::showReprintTicket() { ui_mainview.mainPanel->setCurrentIndex(pageReprintTicket); QTimer::singleShot(500, this, SLOT(setupTicketView())); } void iotposView::cashOut() { bool doit = false; //ASK for security if no lowSecurityMode. if (Settings::lowSecurityMode()) { doit = true; } else { dlgPassword->show(); dlgPassword->clearLines(); dlgPassword->hide(); doit = dlgPassword->exec(); }//else lowsecurity if (doit) { double max = drawer->getAvailableInCash(); if (!max>0) { //KPassivePopup::message( i18n("Error:"),i18n("Cash not available at drawer!"),DesktopIcon("dialog-error", 48), this ); KNotification *notify = new KNotification("information", this); notify->setText(i18n("Cash not available at drawer!")); QPixmap pixmap = DesktopIcon("dialog-error",32); notify->setPixmap(pixmap); notify->sendEvent(); } else { InputDialog *dlg = new InputDialog(this, false, dialogCashOut, i18n("Cash Out"), 0.001, max); if (dlg->exec() ) { Azahar *myDb = new Azahar; myDb->setDatabase(db); CashFlowInfo info; info.amount = dlg->dValue; info.reason = dlg->reason; info.date = QDate::currentDate(); info.time = QTime::currentTime(); info.terminalNum = Settings::editTerminalNumber(); info.userid = loggedUserId; info.type = ctCashOut; //Normal cash-out qulonglong cfId = myDb->insertCashFlow(info); //affect drawer //NOTE: What about CUPS printers? if (Settings::openDrawer() && Settings::smallTicketDotMatrix() && Settings::printTicket() ) drawer->open(); drawer->substractCash(info.amount); drawer->insertCashflow(cfId); QString authBy = dlgPassword->username(); if (authBy.isEmpty()) authBy = myDb->getUserName(1); //default admin. log(loggedUserId, QDate::currentDate(), QTime::currentTime(), i18n("Cash-OUT by %1 at terminal %2 on %3",authBy,Settings::editTerminalNumber(),QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm"))); delete myDb; } delete dlg; } } } void iotposView::cashIn() { bool doit = false; //ASK for security if no lowSecurityMode. if (Settings::lowSecurityMode()) { doit = true; } else { dlgPassword->show(); dlgPassword->clearLines(); dlgPassword->hide(); doit = dlgPassword->exec(); }//else lowsecurity if (doit) { InputDialog *dlg = new InputDialog(this, false, dialogCashOut, i18n("Cash In")); if (dlg->exec() ) { Azahar *myDb = new Azahar; myDb->setDatabase(db); CashFlowInfo info; info.amount = dlg->dValue; info.reason = dlg->reason; info.date = QDate::currentDate(); info.time = QTime::currentTime(); info.terminalNum = Settings::editTerminalNumber(); info.userid = loggedUserId; info.type = ctCashIn; //normal cash-out qulonglong cfId = myDb->insertCashFlow(info); //affect drawer //NOTE: What about CUPS printers? if (Settings::openDrawer() && Settings::smallTicketDotMatrix() && Settings::printTicket() ) drawer->open(); drawer->addCash(info.amount); drawer->insertCashflow(cfId); QString authBy = dlgPassword->username(); if (authBy.isEmpty()) authBy = myDb->getUserName(1); //default admin. log(loggedUserId, QDate::currentDate(), QTime::currentTime(), i18n("Cash-IN [%1] by %2 at terminal %3 on %4",QString::number(info.amount, 'f',2),authBy,Settings::editTerminalNumber(),QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm"))); delete myDb; } delete dlg; } } void iotposView::cashAvailable() { double available = drawer->getAvailableInCash(); KNotification *notify = new KNotification("information", this); notify->setText(i18n("There are <b> %1 in cash </b> available at the drawer.", KGlobal::locale()->formatMoney(available))); QPixmap pixmap = DesktopIcon("dialog-information",32); notify->setPixmap(pixmap); notify->sendEvent(); } void iotposView::log(const qulonglong &uid, const QDate &date, const QTime &time, const QString &text) { Azahar *myDb = new Azahar; myDb->setDatabase(db); myDb->insertLog(uid, date, time, "[ IOTPOS ] "+text); delete myDb; } /** Inserts a S.O. into the buy list, at 50% of its price (a prepayment). ** Or it can be the total payment. **/ void iotposView::addSpecialOrder() { if ( transactionInProgress && (totalSum >0) && specialOrders.isEmpty() ) { KNotification *notify = new KNotification("information", this); notify->setText(i18n("Please finish the current transaction before creating a special order.")); QPixmap pixmap = DesktopIcon("dialog-information",32); notify->setPixmap(pixmap); notify->sendEvent(); return; } //first, if the sale contains another SO, then only the same client is allowed, and we must disable the client selection on the SO editor. bool allowClientSelection = specialOrders.isEmpty(); SpecialOrderInfo soInfo; qulonglong newSOId = 0; SpecialOrderEditor *soEditor = new SpecialOrderEditor(this); soEditor->setModel(productsModel); soEditor->setDb(db); soEditor->setTransId(currentTransaction); soEditor->setUsername(loggedUserName); soEditor->setClientsComboEnabled(allowClientSelection); soEditor->setDeliveryDateTimeEnabled(allowClientSelection); if (!allowClientSelection) { soEditor->setClientName(clientInfo.name); soEditor->setDeliveryDateTime(QDateTime::currentDateTime()); } if (soEditor->exec()) { //get values from dialog soInfo.saleid = currentTransaction; soInfo.name = soEditor->getDescription(); soInfo.qty = soEditor->getQty(); soInfo.price = soEditor->getPrice(); soInfo.cost = soEditor->getCost(); soInfo.notes = soEditor->getNotes(); soInfo.status = stPending; soInfo.units = 1; /// MCH 20DIC09 soInfo.unitStr = ""; soInfo.groupElements = soEditor->getGroupElementsStr(); soInfo.payment = soEditor->getPayment(); soInfo.deliveryDateTime = soEditor->getDeliveryDateTime(); if (soInfo.payment == soInfo.price) soInfo.completePayment = true; else soInfo.completePayment = false; soInfo.dateTime = soEditor->getDateTime(); if (soInfo.payment == soInfo.price) soInfo.completedOnTrNum = currentTransaction; else soInfo.completedOnTrNum = 0; soInfo.clientId = soEditor->getClientId(); soInfo.userId = soEditor->getUserId(); Azahar *myDb = new Azahar; myDb->setDatabase(db); //for the user discount, change user on transaction. clientInfo = myDb->getClientInfo(soInfo.clientId); updateClientInfo(); refreshTotalLabel(); newSOId = myDb->insertSpecialOrder(soInfo); //we need to insert it to get the orderid. if ( newSOId == 0 ) qDebug()<<"Error insertando SO :"<<myDb->lastError(); soInfo.orderid = newSOId; //discount from SO elements soInfo.disc = myDb->getSpecialOrderAverageDiscount(soInfo.orderid)/100; //in percentage. double soDiscount = soInfo.disc * soInfo.payment *soInfo.qty; //add info to the buy list int insertedAtRow = -1; QString codeX = QString("so.%1").arg(QString::number(soInfo.orderid)); QString newName = soInfo.name+"\n"+soEditor->getContentNames(); /// here we insert the product at its payment - can be 50% pre-payment insertedAtRow = doInsertItem(codeX, newName, soInfo.qty, soInfo.payment, soDiscount, soInfo.unitStr); //April 5 2010: Now SO can have DISCOUNTS on its elements... soInfo.insertedAtRow = insertedAtRow; newName = newName.replace("\n", "|"); soInfo.geForPrint = newName; //after inserting so in the db, calculate tax. soInfo.averageTax = myDb->getSpecialOrderAverageTax(soInfo.orderid); //add to the hash specialOrders.insert(soInfo.orderid, soInfo); refreshTotalLabel(); //Saving session. qDebug()<<"** INSERTING A SPECIAL ORDER [updating balance/transaction]"; updateBalance(false); updateTransaction(); //disable client combo box. ui_mainview.groupClient->setDisabled(true); delete myDb; } //finally delete de ui delete soEditor; } void iotposView::specialOrderComplete() { //first ensure we have no pending transaction if ( transactionInProgress && (totalSum >0) ) { KNotification *notify = new KNotification("information", this); notify->setText(i18n("Please finish the current transaction before completing a special order.")); QPixmap pixmap = DesktopIcon("dialog-information",32); notify->setPixmap(pixmap); notify->sendEvent(); return; } SOSelector *dlg = new SOSelector(this); dlg->setDb(db); if (dlg->exec() ) { qulonglong tNum=dlg->getSelectedTicket(); Azahar *myDb = new Azahar; myDb->setDatabase(db); QList<SpecialOrderInfo> soList = myDb->getAllSOforSale(tNum); if (soList.isEmpty()) { KNotification *notify = new KNotification("information", this); notify->setText(i18n("The given ticket number does not contains any special order.")); QPixmap pixmap = DesktopIcon("dialog-information",32); notify->setPixmap(pixmap); notify->sendEvent(); return; } //continue.. its time to complete QStringList paidOrders; paidOrders << i18n("These special orders cannot be completed because:"); int soCompletePayments = 0; qulonglong clientIdForDiscount = 0; foreach(SpecialOrderInfo soInfo, soList) { if ( soInfo.status == stDelivered || soInfo.status == stCancelled) { QString stStr; if (soInfo.status == stCancelled) stStr = i18n("<b>is Cancelled</b>"); else stStr = i18n("is already <b>Delivered</b>"); paidOrders << i18n("%1 %2.", soInfo.name, stStr); } else { //first check if the so is already delivered or cancelled if (soInfo.status == stDelivered || soInfo.status == stCancelled) { continue; //HEY PURIST, WHEN I GOT SOME TIME I WILL CLEAN IT } if (soInfo.payment == soInfo.price) { soCompletePayments++; myDb->specialOrderSetStatus(soInfo.orderid, stDelivered); qDebug()<<"This special order is completeley paid and marked as delivered without emiting a ticket."; KNotification *notify = new KNotification("information", this); notify->setText(i18n("The special order %1 in ticket %2 is completely paid. Marked as delivered.", soInfo.orderid, soInfo.saleid)); QPixmap pixmap = DesktopIcon("dialog-information",32); notify->setPixmap(pixmap); notify->sendEvent(); continue; //dont insert this... } qDebug()<<"Going to insert so in the list."; clientIdForDiscount = soInfo.clientId; //insert each so to the list. int insertedAtRow = -1; QString codeX = QString("so.%1").arg(QString::number(soInfo.orderid)); QList<ProductInfo> pList = myDb->getSpecialOrderProductsList(soInfo.orderid); QString newName = soInfo.name; foreach(ProductInfo inf, pList) { QString unitStr; if (inf.units == 1 ) unitStr=" "; else unitStr = inf.unitStr; newName += "\n " + QString::number(inf.qtyOnList) + " "+ unitStr +" "+ inf.desc; } newName = newName+"\n"+i18n("Notes:")+soInfo.notes; ///discount from SO elements double toPay = soInfo.price-soInfo.payment; double soDiscount = soInfo.disc * toPay * soInfo.qty; /// here we insert the product with the appropiate payment. insertedAtRow = doInsertItem(codeX, newName, soInfo.qty, toPay, soDiscount, soInfo.unitStr); //modify SpecialOrder info for database update. soInfo.insertedAtRow = insertedAtRow; soInfo.payment = soInfo.price-soInfo.payment; //the final payment is what we save on db. soInfo.completePayment = true; soInfo.status = stReady; //status = ready to deliver. soInfo.completedOnTrNum = currentTransaction; newName = newName.replace("\n", "|"); soInfo.geForPrint = newName; ///after inserting so in the db, calculate tax. soInfo.averageTax = myDb->getSpecialOrderAverageTax(soInfo.orderid); //add to the hash specialOrders.insert(soInfo.orderid, soInfo); refreshTotalLabel(); } //else if cancelled or delivered } //foreach soInfo if (clientIdForDiscount == 0) { // no client id.. this happens on completeley paid orders. clientInfo = clientsHash.value(myDb->getMainClient()); clientIdForDiscount = clientInfo.id; } else clientInfo = myDb->getClientInfo(clientIdForDiscount); // See if there was an occasional discount on the originating transaction to apply it to the PROFIT. lastDiscount = 0; lastDiscount = myDb->getTransactionDiscMoney(tNum); qDebug()<<" Originating transaction discount:"<<lastDiscount<<" applying it to the profit."; updateClientInfo(); refreshTotalLabel(); if (paidOrders.count()> 1) { // the first is the pre-message KNotification *notify = new KNotification("information", this); notify->setText(paidOrders.join("\n")); QPixmap pixmap = DesktopIcon("dialog-information",32); notify->setPixmap(pixmap); notify->sendEvent(); } //Saving session. qDebug()<<"** COMPLETING A SPECIAL ORDER [updating balance/transaction]"; updateBalance(false); updateTransaction(); //disable clients combo box ui_mainview.groupClient->setDisabled(true); delete myDb; } } void iotposView::lockScreen() { //To allow cashier to suspend sales for a moment. There is still a concept to implement: save uncompleted sales to allow retake later on (minutes, hours, days). emit signalDisableUI(); emit signalDisableLogin(); QString msg = i18n("<b>This terminal is locked.</b> <br><i>Please enter the user's password to unlock it</i>."); lockDialog->showDialog(msg); //Saving session. qDebug()<<"** LOCKING SCREEN [updating balance/transaction]"; updateBalance(false); updateTransaction(); } void iotposView::unlockScreen() { //get password from dialog. QString pwd = lockDialog->getPassword(); if (!pwd.isEmpty()) { //get user info Azahar *myDb = new Azahar; myDb->setDatabase(db); UserInfo uInfo = myDb->getUserInfo(loggedUserId); delete myDb; QString givenPass = Hash::password2hash((uInfo.salt+pwd).toLocal8Bit()); if (givenPass == uInfo.password) { //finally close dialog lockDialog->hideDialog(); lockDialog->cleanPassword(); //unlock ui emit signalEnableUI(); emit signalEnableLogin(); ui_mainview.editItemCode->setFocus(); setupGridView(); } else { lockDialog->cleanPassword(); lockDialog->shake(); } } } //For save sessions void iotposView::insertBalance() { Azahar *myDb = new Azahar; myDb->setDatabase(db); //This creates an empty balance BalanceInfo info; info.id = 0; info.dateTimeStart = drawer->getStartDateTime(); info.dateTimeEnd = info.dateTimeStart; info.userid = loggedUserId; info.username = loggedUser; info.initamount = drawer->getInitialAmount(); info.in = drawer->getInAmount(); info.out = drawer->getOutAmount(); info.cash = drawer->getAvailableInCash(); info.card = drawer->getAvailableInCard(); info.terminal = Settings::editTerminalNumber(); info.transactions = ""; info.cashflows = ""; info.done = false; currentBalanceId = myDb->insertBalance(info); qDebug()<<"Inserted the new BALANCE #"<<currentBalanceId; delete myDb; } void iotposView::updateBalance(bool finish) { Azahar *myDb = new Azahar; myDb->setDatabase(db); //got info from drawer.. BalanceInfo info; info.id = currentBalanceId; info.dateTimeStart = drawer->getStartDateTime(); info.dateTimeEnd = QDateTime::currentDateTime(); info.userid = loggedUserId; info.username = loggedUser; info.initamount = drawer->getInitialAmount(); info.in = drawer->getInAmount(); info.out = drawer->getOutAmount(); info.cash = drawer->getAvailableInCash(); info.card = drawer->getAvailableInCard(); info.terminal = Settings::editTerminalNumber(); info.done = finish; //only true when finishing the Balace. QStringList tmpList; foreach(qulonglong tid, drawer->getTransactionIds()) { tmpList << QString::number(tid); } info.transactions = tmpList.join(","); tmpList.clear(); qDebug()<< __FUNCTION__ <<" Transactions:"<<info.transactions; foreach(qulonglong tid, drawer->getCashflowIds()) { tmpList << QString::number(tid); } info.cashflows = tmpList.join(","); qDebug()<<"Updating balance #"<<currentBalanceId; if (!myDb->updateBalance(info)) qDebug()<<"Error updating balance.."; delete myDb; } void iotposView::updateTransaction() { //fill info TransactionInfo info; info.id = currentTransaction; info.balanceId= currentBalanceId; info.type = tSell; info.amount = totalSum; if (!ui_mainview.groupSaleDate->isHidden()) info.date = ui_mainview.editTransactionDate->dateTime().date(); else info.date = QDate::currentDate(); info.time = QTime::currentTime(); info.paywith = 0; info.changegiven = 0; info.paymethod = pCash; info.state = tNotCompleted; info.userid = loggedUserId; info.clientid = clientInfo.id; info.cardnumber= "NA"; info.cardauthnum= "NA"; info.disc = clientInfo.discount; info.discmoney = discMoney; info.points = buyPoints; info.terminalnum= Settings::editTerminalNumber(); info.providerid=1; double profit = 0; double cant = 0; QStringList tmpList; foreach(ProductInfo pi, productsHash) { profit += (pi.price - pi.cost - pi.disc) * pi.qtyOnList; if ( pi.units == uPiece ) cant += pi.qtyOnList; else cant += 1; tmpList << QString::number(pi.code) + "/" + QString::number(pi.qtyOnList); } info.itemlist = tmpList.join(","); //Only save normal products. Its almost DEPRECATED. tmpList.clear(); foreach(SpecialOrderInfo soi, specialOrders) { profit += (soi.price - soi.cost) * soi.qty; if ( soi.units == uPiece ) cant += soi.qty; else cant += 1; tmpList << QString::number(soi.orderid) + "/" + QString::number(soi.qty); } info.specialOrders= tmpList.join(","); info.itemcount = cant; info.utility = profit; //info.groups = ""; //DEPRECATED. //WARNING: Here transaction.totalTaxes is missing! Detected during updateTransaction() called on suspendReservation()/reserveItems(). totalTaxes is assigned a garbage number (example, 291.9282828293834e-300) Azahar *myDb = new Azahar; myDb->setDatabase(db); myDb->updateTransaction(info); delete myDb; } void iotposView::suspendSale() { qulonglong count = specialOrders.count() + productsHash.count(); qDebug()<<"finishingReservation:"<<finishingReservation<<" startingReservation:"<<startingReservation; Azahar *myDb = new Azahar; myDb->setDatabase(db); ReservationInfo tRInfo = myDb->getReservationInfoFromTr( currentTransaction ); delete myDb; if ( operationStarted && count>0 ) { qulonglong tmpId = currentTransaction; qDebug()<<"THE SALE HAS BEEN SUSPENDED. Id="<<tmpId; // save transaction and balance updateTransaction(); updateBalance(false); // clear widgets startAgain(); if ( tRInfo.transaction_id == currentTransaction ) { qDebug()<<"The current transaction is reserved, doing a reservation suspend."; // Change transaction STATUS to tReserved. myDb->setTransactionStatus(currentTransaction, tReserved); //reservationPayment qDebug()<<"Reservation Payment:"<<reservationPayment; } //inform the user KNotification *notify = new KNotification("information", this); notify->setText(i18n("The sale %1 has been sucessfully suspended.", tmpId)); QPixmap pixmap = DesktopIcon("dialog-information",32); notify->setPixmap(pixmap); notify->sendEvent(); } ui_mainview.stackedWidget_3->setCurrentIndex(1); ui_mainview.listView->scrollToTop(); } //This will resume the sale, using a new balanceid. void iotposView::resumeSale() { Azahar *myDb = new Azahar; myDb->setDatabase(db); ResumeDialog *dlg = new ResumeDialog(this); dlg->setUserId(loggedUserId); //note: this must be called before setDb() dlg->setDb(db); if (dlg->exec()) { //get data QList<ProductInfo> pList = dlg->getProductsList(); QList<SpecialOrderInfo> sList = dlg->getSOList(); qulonglong trNumber = dlg->getSelectedTransaction(); qulonglong clientId = dlg->getSelectedClient(); //Check if there is a transaction, and suspend it. suspendSale(); currentTransaction = trNumber; emit signalUpdateTransactionInfo(); clientInfo = myDb->getClientInfo(clientId); updateClientInfo(); refreshTotalLabel(); //NOTE: change sale date ? //get each product - the availability and group verification will do the insertItem method foreach(ProductInfo info, pList) { QString qtyXcode = QString::number(info.qtyOnList) + "*" + QString::number(info.code); insertItem(qtyXcode); } foreach(SpecialOrderInfo info, sList) { int insertedAtRow = -1; QString codeX = QString("so.%1").arg(QString::number(info.orderid)); //get formated content names for printing/list. QStringList list; QStringList strlTmp = info.groupElements.split(","); foreach(QString str, strlTmp) { QString itemCode = str.section('/',0,0); //.toULongLong(); double itemQty = str.section('/',1,1).toDouble(); //get item info ProductInfo itemInfo = myDb->getProductInfo(itemCode); itemInfo.qtyOnList = itemQty; QString unitStr; if (itemInfo.units == 1 ) unitStr=""; else unitStr = itemInfo.unitStr; list.append(" "+QString::number(itemInfo.qtyOnList)+" "+unitStr+" "+ itemInfo.desc); } //append NOTES for the SO. list.append("\n"+i18n("Notes: %1", info.notes+" \n")); //end of formated content names for so QString newName = info.name+"\n" + list.join("\n"); insertedAtRow = doInsertItem(codeX, newName, info.qty, info.payment, 0, info.unitStr); info.insertedAtRow = insertedAtRow; newName = newName.replace("\n", "|"); info.geForPrint = newName; //change delivery datetime. //get original date lapse between so-creation date and delivery date. int lap = info.dateTime.date().daysTo( info.deliveryDateTime.date() ); info.deliveryDateTime = QDateTime::currentDateTime().addDays(lap); qDebug()<<"lap:"<<lap; //add to the hash specialOrders.insert(info.orderid, info); //myDb->updateSpecialOrder(info); //In case this sale is re-suspended the delivery lapse is going to be increased... //this update was moved to finishCurrentTransaction... } updateBalance(false); updateTransaction(); } refreshTotalLabel(); delete myDb; } void iotposView::changeSOStatus() { if ( transactionInProgress && (totalSum >0) ) { KNotification *notify = new KNotification("information", this); notify->setText(i18n("Please finish the current transaction before changing state for a special order.")); QPixmap pixmap = DesktopIcon("dialog-information",32); notify->setPixmap(pixmap); notify->sendEvent(); return; } SOStatus *dlg = new SOStatus(this); dlg->setDb(db); if (dlg->exec()) { int status = dlg->getStatusId(); qulonglong orderid = dlg->getSelectedTicket(); Azahar *myDb = new Azahar; myDb->setDatabase(db); myDb->soTicketSetStatus(orderid, status); delete myDb; }//dlg exec } //NOTE: Aug 6 2011: Now occasionalDiscount can be in dollar and cents. void iotposView::occasionalDiscount() { bool continuar=false; oDiscountMoney = 0; if (Settings::lowSecurityMode()) { //qDebug()<<"LOW security mode"; continuar=true; } else {// qDebug()<<"NO LOW security mode"; dlgPassword->show(); dlgPassword->hide(); dlgPassword->clearLines(); continuar = dlgPassword->exec(); } if (continuar) { //SHOW THE NEW DISCOUNT PANEL discountPanel->showPanel(); //the new code is at applyOccasionalDiscount(). } } void iotposView::applyOccasionalDiscount() { ///NOTE: FIXME! The nonDiscountable items should not be discounted with dollar discount or Percentage discount. /// Now the problem is with special Orders. How to allow/disallow discounts for them? //validate discount: the input has a proper validator. if (ui_mainview.rbPercentage->isChecked()) { oDiscountMoney = 0; //this is 0 when applying a percentage discount. clientInfo.discount = ui_mainview.editDiscount->text().toDouble(); } else if (ui_mainview.rbMoney->isChecked()) { oDiscountMoney = ui_mainview.editDiscount->text().toDouble(); clientInfo.discount = 0; } else if (ui_mainview.rbPriceChange->isChecked()) { double priceDiff = 0; //clientInfo.discount = 0; //reset FIXED: when gdiscount is applied then product price, the gDiscount is cleared! //oDiscountMoney = 0; //reset ///To change price to an item, it must be selected (obviously already in the purchase list). Only to normal items, no SpecialOrders. ///Discount to the whole sale is allowed too. if (ui_mainview.tableWidget->currentRow()!=-1 && ui_mainview.tableWidget->selectedItems().count()>4) { int row = ui_mainview.tableWidget->currentRow(); QTableWidgetItem *item = ui_mainview.tableWidget->item(row, colCode); qulonglong code = item->data(Qt::DisplayRole).toULongLong(); if (code <= 0) { //it is an special order, not a normal product. ///TODO: Implement price change for Special Orders, or is it not a good idea? } qDebug()<<"Selected code for changing price: "<<code; if (code > 0) { ProductInfo info = productsHash.take(code); //insert it later... ///NOTE: price change will be applied over the normal price. Not applying item discounts. If exists any it will be cleared. if (info.isNotDiscountable) { discountPanel->hidePanel(); notifierPanel->setSize(350,150); notifierPanel->setOnBottom(false); notifierPanel->showNotification("<b>Cannot change price</b> to product marked as not discountable.",5000); ui_mainview.editItemCode->setFocus(); setupGridView(); return; } priceDiff = info.price - ui_mainview.editDiscount->text().toDouble(); //NOTE: A price change to higher the price would give a negative priceDiff. if (priceDiff < 0) { qDebug()<<"Applying a price change to make the product's price higher"; } info.disc = priceDiff; // set item discount money. discPercentage will be zero. info.discpercentage = 0; info.validDiscount = false; ///to detect the difference between offers and price changes. productsHash.insert(code, info); //reinsert it with the new discount. ///update purchase list! updateItem(info); //LOG the price change! Azahar *myDb = new Azahar; myDb->setDatabase(db); QString authBy = dlgPassword->username(); if (authBy.isEmpty()) authBy = myDb->getUserName(1); //default admin. log(loggedUserId, QDate::currentDate(), QTime::currentTime(), i18n("Changing price to product %1, from %2 to %3. Authorized by %4", code, info.price, ui_mainview.editDiscount->text().toDouble(), authBy)); delete myDb; qDebug()<<QString("Changing price to: %1, from %2 to %3.").arg(code).arg(info.price).arg(ui_mainview.editDiscount->text().toDouble()); } else { // SO cannot be price changed. notifierPanel->setSize(350,150); notifierPanel->setOnBottom(false); notifierPanel->showNotification("<b>Cannot change price</b> to Special Orders, only to normal products.",5000); } } else { notifierPanel->setSize(350,150); notifierPanel->setOnBottom(false); notifierPanel->showNotification("First <b>select a product</b> to <i>change the price</i> from the sale list.",5000); } ui_mainview.editItemCode->setFocus(); setupGridView(); refreshTotalLabel(); ui_mainview.editDiscount->clear(); discountPanel->hidePanel(); return; //exit the method, we dont want to run the code at line 4641 and below. } else { //by coupon. //FIXME:CODE IT! oDiscountMoney = 0; //reset clientInfo.discount = 0; //reset } qDebug()<<"Continuing with discount..."; //clientInfo.discount = discPercent; updateClientInfo(); refreshTotalLabel(); Azahar *myDb = new Azahar; myDb->setDatabase(db); QString authBy = dlgPassword->username(); if (authBy.isEmpty()) authBy = myDb->getUserName(1); //default admin. log(loggedUserId, QDate::currentDate(), QTime::currentTime(), i18n("Applying occasional discount. Authorized by %1",authBy)); delete myDb; //At the end, clear the widget. Except for the type. ui_mainview.editDiscount->clear(); discountPanel->hidePanel(); } //NOTE: Reservations are not treated as sales until they are completed. The amount payment at the reservation is // treated as a cash-in, without any transaction implied. The transaction used is kept at NotCompleted state. void iotposView::reserveItems() { TicketInfo ticket; QList<TicketLineInfo> ticketLines; double payWith = 0.0; double changeGiven = 0.0; QString authnumber = ""; QString cardNum = ""; QString paidStr = "'[Not Available]'"; QStringList groupList; reservationPayment = 0; //reset before Azahar *myDb = new Azahar; myDb->setDatabase(db); if (productsHash.isEmpty()) return; //we do not have anything to do. //check if there is a reservation with the same transaction to avoid a duplicate or buggy behavior. ReservationInfo tRInfo = myDb->getReservationInfoFromTr( currentTransaction ); if ( tRInfo.transaction_id == currentTransaction ) { notifierPanel->setSize(350,150); notifierPanel->setOnBottom(false); notifierPanel->showNotification("<b>Cannot reserve this transaction</b> because it is <i>already reserved</i>.<br>You may finish this reservation or suspend sale if you selected this sale by mistake.",8000); qDebug()<<"This transaction already has a reservation. Tr id:"<<currentTransaction<<" Reservation Id:"<<tRInfo.id; return; } startingReservation = true; finishingReservation= false; TransactionInfo tInfo = myDb->getTransactionInfo(currentTransaction); qDebug()<<"[*] SAVING PROFIT TO RESERVATION $:"<<tInfo.utility; reservationPayment = ui_mainview.editAmount->text().toDouble(); payWith = reservationPayment; //change given is allways 0. //check if there are items in the list. Only on normal products, not SO. if (!productsHash.isEmpty()) { ReservationInfo rInfo; rInfo.id=0; rInfo.client_id = clientInfo.id; rInfo.transaction_id = currentTransaction; rInfo.date = QDate::currentDate(); rInfo.status = rPending; //get Payment Amount. rInfo.payment = reservationPayment; // total without payment rInfo.total = subTotalSum; // This amount is WITHOUT TAXES. rInfo.totalTaxes = totalTax; rInfo.profit = tInfo.utility; rInfo.discount = globalDiscount*100; // gDiscountPercentage is .10 for 10% rInfo.item_discounts = ""; QStringList discItems; qDebug()<< __FUNCTION__ <<" Reservation Amount:"<< rInfo.payment<<" Total :"<<rInfo.total<<" Taxes:"<< rInfo.totalTaxes; if (rInfo.payment <= 0) { //TODO: Replace this notify with a mibitLineEdit->VIBRAR, y mibitTip KNotification *notify = new KNotification("information", this); notify->setText(i18n("Please Enter the reservation Amount in the Payment Amount and try again.")); QPixmap pixmap = DesktopIcon("dialog-information",32); notify->setPixmap(pixmap); notify->sendEvent(); ui_mainview.editAmount->setFocus(); return; } Azahar *myDb = new Azahar; myDb->setDatabase(db); double pDiscounts=0; double cantidad=0; foreach (ProductInfo pi, productsHash) { //Decrement product-qty from inventory. if (pi.isAGroup) myDb->decrementGroupStock(pi.code, pi.qtyOnList, QDate::currentDate() ); else myDb->decrementProductStock(pi.code, pi.qtyOnList, QDate::currentDate() ); //get item data pDiscounts+= pi.disc * pi.qtyOnList; if (pi.units == uPiece) cantidad += pi.qtyOnList; else cantidad += 1; // :) QString iname = ""; if (!pi.groupElementsStr.isEmpty()) { QStringList lelem = pi.groupElementsStr.split(","); foreach(QString ea, lelem) { if (Settings::printPackContents()) { qulonglong c = ea.section('/',0,0).toULongLong(); double q = ea.section('/',1,1).toDouble(); ProductInfo p = myDb->getProductInfo(QString::number(c)); QString unitStr; if (p.units == 1 ) unitStr=" "; else unitStr = p.unitStr; iname += "\n " + QString::number(q) + " "+ unitStr +" "+ p.desc; } } } iname = iname.replace("\n", "|"); // add line to ticketLines TicketLineInfo tLineInfo; tLineInfo.qty = pi.qtyOnList; tLineInfo.unitStr = pi.unitStr; tLineInfo.isGroup = false; if (pi.isAGroup) { tLineInfo.geForPrint =iname; tLineInfo.completePayment = true; tLineInfo.payment = 0; tLineInfo.isGroup = true; } tLineInfo.desc = pi.desc; tLineInfo.price = pi.price; tLineInfo.disc = pi.disc*pi.qtyOnList; tLineInfo.total = (pi.price - pi.disc) * pi.qtyOnList; tLineInfo.tax = (pi.tax + pi.extratax); //Now in %. //pi.totaltax*pi.qtyOnList; //HERE, pi.totaltax is in MONEY, not percentage. ticketLines.append(tLineInfo); //adding info for each product discount if any.. if (pi.disc > 0) discItems.append(QString("%1/%2").arg(pi.code).arg(pi.disc)); } //for each product //now we have the discItems, assign to the rInfo. rInfo.item_discounts = discItems.join(","); //create the reservation record qulonglong rId = myDb->insertReservation(rInfo); //Register the cash-in CashFlowInfo info; info.amount = rInfo.payment; info.reason = i18n("Reservation #%1 [tr. %2]", rId, currentTransaction); info.date = QDate::currentDate(); info.time = QTime::currentTime(); info.terminalNum = Settings::editTerminalNumber(); info.userid = loggedUserId; info.type = ctCashIn; qulonglong cfId = myDb->insertCashFlow(info); //affect drawer if (Settings::openDrawer() && Settings::smallTicketDotMatrix() && Settings::printTicket() ) drawer->open(); if (ui_mainview.checkCash->isChecked()) { drawer->addCash(info.amount); drawer->insertCashflow(cfId); drawer->substractCash(changeGiven); //drawer->incCashTransactions(); //it is not a transaction. } else { drawer->addCard(payWith); drawer->insertCashflow(cfId); } //write a log QString authBy = dlgPassword->username(); if (authBy.isEmpty()) authBy = myDb->getUserName(1); //default admin. log(loggedUserId, QDate::currentDate(), QTime::currentTime(), i18n("Cash-IN [%1] for RESERVATION [%5] by %2 at terminal %3 on %4",QString::number(info.amount, 'f',2),authBy,Settings::editTerminalNumber(),QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm")).arg(rId)); //end cash-in //add the reservation payment -- Dec 15 2011. Every payment must be registered, even the first one. The sum should be equal to the transaction total+taxes myDb->addReservationPayment(rId, rInfo.payment); ui_mainview.editAmount->setStyleSheet(""); //ui_mainview.editCardNumber->setStyleSheet(""); //TODO:PRINT A TICKET - Print it twice? one for client other for store (stick it at the product) // investigate how to manipulate printer settings (cups) NOTE: See at Credits code, there is an answer. ticket.isAReservation = true; ticket.reservationStarted = true; ticket.reservationPayment = rInfo.payment; ticket.reservationId = rId; ticket.purchaseTotal = rInfo.total; ticket.datetime = QDateTime::currentDateTime(); //NOTE:Reservations are not DATE CHANGEABLE. QString realSubtotal; if (Settings::addTax()) realSubtotal = KGlobal::locale()->formatMoney(subTotalSum-discMoney+pDiscounts, QString(), 2); else realSubtotal = KGlobal::locale()->formatMoney(subTotalSum-totalTax+discMoney+pDiscounts, QString(), 2); //FIXME: es +discMoney o -discMoney?? qDebug()<<"\n********** Total Taxes:"<<totalTax<<" total Discount:"<<discMoney<<" Prod Discounts:"<<pDiscounts; ticket.number = currentTransaction; ticket.subTotal = realSubtotal; //This is the subtotal-taxes-discount ticket.total = reservationPayment; qDebug()<<" *************** totalSum:"<<totalSum; ticket.change = changeGiven; ticket.paidwith = payWith; ticket.itemcount = cantidad; ticket.cardnum = cardNum; ticket.cardAuthNum = authnumber; ticket.paidWithCard = ui_mainview.checkCard->isChecked(); ticket.clientDisc = clientInfo.discount; ticket.clientDiscMoney = discMoney; ticket.buyPoints = buyPoints; ticket.clientPoints = clientInfo.points; ticket.lines = ticketLines; ticket.clientid = clientInfo.id; ticket.hasSpecialOrders = false; ticket.completingSpecialOrder = false; ticket.totalTax = totalTax; ticket.terminal = QString::number(Settings::editTerminalNumber()); //TODO: Add TERMS AND CONDITIONS OF RESERVATIONS to the ticket ?? // Suspend Reservation (save balance, transaction, clear widgets...) suspendReservation(); // Change transaction STATUS to tReserved. myDb->setTransactionStatus(rInfo.transaction_id, tReserved); //send print ticket data printTicket(ticket); printTicket(ticket); } else { //Cannot reserve empty product list! KNotification *notify = new KNotification("information", this); notify->setText(i18n("Cannot make a reservation, no products on the list. Special Orders are not considered.")); QPixmap pixmap = DesktopIcon("dialog-information",32); notify->setPixmap(pixmap); notify->sendEvent(); } delete myDb; } //NOTE: Here the store owner/admin needs to know that when iotpos makes a product reservation the product qty in stock is decremented. // So, if the reserved product is not completed, the item is physically in the store but not in stock. It must be re-stocked, which // is done with a stockCorrection with a reason of "Reservation not completed or cancelled." void iotposView::suspendReservation() { qulonglong count = productsHash.count(); if ( operationStarted && count>0 ) { qulonglong tmpId = currentTransaction; qDebug()<<"THE TRANSACTION HAS BEEN RESERVED. Id="<<tmpId; // save transaction and balance updateTransaction(); updateBalance(false); // clear widgets startAgain(); //inform the user KNotification *notify = new KNotification("information", this); notify->setText(i18n("The sale %1 has been sucessfully reserved.", tmpId)); QPixmap pixmap = DesktopIcon("dialog-information",32); notify->setPixmap(pixmap); notify->sendEvent(); } } void iotposView::resumeReservation() { qDebug()<<"finishingReservation:"<<finishingReservation<<" startingReservation:"<<startingReservation; if (finishingReservation || startingReservation) return; Azahar *myDb = new Azahar; myDb->setDatabase(db); ReservationsDialog *dlg = new ReservationsDialog(this, drawer, loggedUserId); dlg->setDb(db); QString itemDiscounts; double reservProfit=0; if (dlg->exec()) { // Until now, the transaction has the total of totalREAL - reservation.payment. // When doing the finishTransaction we need to update the total to the REAL TOTAL only // We can use a flag to indicate to do such thing on the finishCurrentTransaction() method. startingReservation = false; finishingReservation= true; //get data QList<ProductInfo> pList = dlg->getProductsList(); qulonglong trNumber = dlg->getSelectedTransaction(); qulonglong clientId = dlg->getSelectedClient(); reservationPayment = dlg->getReservationPayment(); reservationId = dlg->getSelectedReservation(); itemDiscounts = dlg->getItemDiscounts(); reservProfit = dlg->getReservationProfit(); //Check if there is a transaction, and suspend it before resume the reservation. suspendSale(); currentTransaction = trNumber; emit signalUpdateTransactionInfo(); clientInfo = myDb->getClientInfo(clientId); updateClientInfo(); refreshTotalLabel(); //HERE the availability does not matter, the item is Physically Reserved. foreach(ProductInfo info, pList) { QString qtyXcode = QString::number(info.qtyOnList) + "*" + QString::number(info.code); availabilityDoesNotMatters = true; insertItem(qtyXcode); availabilityDoesNotMatters = false; } //once inserted items, see if any had discount on the original sale if (!itemDiscounts.isEmpty()) { QStringList lista = itemDiscounts.split(","); foreach(QString elem, lista){ QStringList lista2 = elem.split("/"); //get from the productsHash the products with discounts. THE DISCOUNT IS IN MONEY for EACH PIECE/QTY. ProductInfo p = productsHash.take( lista2[0].toULongLong() ); if (lista2.count() == 2) { double pdisc = lista2[1].toDouble(); if ( pdisc > 0 ) { qDebug()<<"P.disc:"<<p.disc<<" p.validdiscount:"<<p.validDiscount<<" discpercentage:"<<p.discpercentage; p.disc = pdisc; p.discpercentage=0; p.validDiscount=false; //emulating price change... productsHash.insert(p.code, p); //refresh item line updateItem(p); } } } } doNotAddMoreItems = true; qDebug()<<"DoNotAddMoreItems = "<<doNotAddMoreItems; updateBalance(false); updateTransaction(); //save reservationProfit on transaction TransactionInfo t = myDb->getTransactionInfo(currentTransaction); t.utility = reservProfit; myDb->updateTransaction(t); // Next is a comment for the time the transaction is fihising // TODO PRINT TICKET: // When printing ticket, the total is for the total value of the products (without the reservation payment). // We need (for accountants) the total to be real on the transaction info. // But, write a note on the ticket saying that a reservation payment of $X.XX was done. } delete myDb; delete dlg; } void iotposView::postponeReservation() { //this is to save the transaction with the tReserved state, instead of cancelTransaction. Azahar *myDb = new Azahar; myDb->setDatabase(db); myDb->setTransactionReservationStatus(getCurrentTransaction()); delete myDb; } //TODO: Print a ticket for the reservation payment, but only when calling this method, not the myDb->addReservationPayment() void iotposView::addReservationPayment() { //This is used to add payments to a reservation without totally paying it. if (finishingReservation || startingReservation) { KNotification *notify = new KNotification("information", this); notify->setText(i18n("You need to finish or suspend the current sale or reservation before adding a payment for a reservation.")); QPixmap pixmap = DesktopIcon("dialog-information",32); notify->setPixmap(pixmap); notify->sendEvent(); return; } Azahar *myDb = new Azahar; myDb->setDatabase(db); ReservationsDialog *dlg = new ReservationsDialog(this, drawer, loggedUserId); dlg->setDb(db); if (dlg->exec()) { qulonglong rId = dlg->getSelectedReservation(); //check if the reservation is not fully paid. ReservationInfo rInfo = myDb->getReservationInfo(rId); //payments = myDb->getReservationPayments(rId); if (rInfo.payment < rInfo.total+rInfo.totalTaxes) { double maxAmount = (rInfo.total+rInfo.totalTaxes) - rInfo.payment; double amn = 0; qDebug()<<"MAX AMOUNT:"<<maxAmount; //get amount InputDialog *dlgA = new InputDialog(this, false, dialogMoney, i18n("Enter the amount to pay to the reservation. The Maximum amount is %1", maxAmount), 0.01, maxAmount); dlgA->setEnabled(true); if (dlgA->exec() ) { amn = dlgA->dValue; //now apply payment myDb->addReservationPayment(rId, amn); //now modify reservation, to increment payment. myDb->setReservationPayment(rId, rInfo.payment+amn); qDebug()<<"Added a reservation payment. Reservation #"<<rId<<" Amount paid:"<<amn; //cash-in. insertCashInForReservationPayment(rId, amn); } delete dlgA; } else { qDebug()<<"The selected reservation cannot be paid because it is already paid."; } } delete dlg; delete myDb; } void iotposView::insertCashInForReservationPayment(const qulonglong &rid, const double &amount) { Azahar *myDb = new Azahar; myDb->setDatabase(db); CashFlowInfo info; info.amount = amount; info.reason = i18n("Payment for Reservation %1", rid); info.date = QDate::currentDate(); info.time = QTime::currentTime(); info.terminalNum = Settings::editTerminalNumber(); info.userid = loggedUserId; info.type = ctCashInReservation; qulonglong cfId = myDb->insertCashFlow(info); //affect drawer //NOTE: What about CUPS printers? if (Settings::openDrawer() && Settings::smallTicketDotMatrix() && Settings::printTicket() ) drawer->open(); drawer->addCash(amount); drawer->insertCashflow(cfId); QString authBy = loggedUserName; log(loggedUserId, QDate::currentDate(), QTime::currentTime(), i18n("Cash-IN-ReservationPayment [%1] for reservation %5 by %2 at terminal %3 on %4",QString::number(amount, 'f',2),authBy,Settings::editTerminalNumber(),QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm"), rid)); delete myDb; } //-----------CREDITS----------------- ///NOTE & WARNING: Credits are linked to clients. If a client ID changes, THE CREDITS MUST BE CHANGED TOO! void iotposView::showCredits() { ui_mainview.editClientIdForCredit->clear(); ui_mainview.creditContent->clear(); ui_mainview.creditPaymentWidget->hide(); ui_mainview.editCreditTendered->clear(); ui_mainview.lblCreditChange->setText("0.0"); creditPanel->showPanel(); ui_mainview.editClientIdForCredit->setFocus(); crInfo.id = 0; crClientInfo.id = 0; } void iotposView::filterClientForCredit() { //modifyClientsFilterModel(); QString searched = ui_mainview.editClientIdForCredit->text(); QString searchedTrimmed = searched.split(" -- ").at(0).trimmed(); ui_mainview.editClientIdForCredit->setText(searchedTrimmed); //The CODE only, set this in the lineedit... qDebug()<<"-SEARCHED TEXT:"<<searched<<" TRIMMED:"<<searchedTrimmed; //if (clientsModel->rowCount() == 1){ // QString clientName = clientsModel->record(0).value("name").toString(); //clientsModel->data(clientsModel->index(0,fieldCode)).toString(); // QString clientCode = clientsModel->record(0).value("code").toString(); //clientsModel->data(clientsModel->index(0,fieldName)).toString(); // QString searched = ui_mainview.editClientIdForCredit->text(); // QString searchedTrimmed = searched.split(" -- ").at(0).trimmed(); // if (searched == clientName || searched == clientCode ){ // qDebug()<<"SEARCHED TEXT:"<<searched<<" SELECTED CLIENT:"<<clientName<<" Selected CODE:"<<clientCode<<" TRIMMED:"<<searchedTrimmed; // ui_mainview.editClientIdForCredit->selectAll(); // } //} QString clientCode = ui_mainview.editClientIdForCredit->text(); if (clientCode.isEmpty() || clientCode == " "){ //clean filter ui_mainview.creditContent->clear();//clear totals for customer credits crInfo.id =0; crClientInfo.id = 0; } else { //search by client code (alphanum, 0000001 and not 1) Azahar *myDb = new Azahar; myDb->setDatabase(db); crClientInfo = myDb->getClientInfo(clientCode); crInfo = myDb->getCreditInfoForClient(crClientInfo.id); //this returns a new credit if no one found for that client. qDebug()<<__FUNCTION__<<"Getting credit info for clientId:"<<crInfo.clientId<<" -- $"<<crInfo.total; delete myDb; //calculate total for unpaid customer credits calculateTotalForClient(); ui_mainview.creditPaymentWidget->show(); } } void iotposView::filterClient() { QString searched = ui_mainview.editClient->text(); QString searchedTrimmed = searched.split(" -- ").at(0).trimmed(); ui_mainview.editClient->setText(searchedTrimmed); //The CODE only, set this in the lineedit... QString clientCode = searchedTrimmed; qDebug()<<"Filtering Clients | SEARCHED TEXT:"<<searched<<" TRIMMED:"<<searchedTrimmed<<" Code:"<<clientCode; if (clientCode.isEmpty() || clientCode == " "){ //clean filter //do not anything now. } else { //search by client code (alphanum, 0000001 and not 1) clientChanged(); //refresh information, client code is at the edit line. } } void iotposView::createClient() { Azahar *myDb = new Azahar; myDb->setDatabase(db); if (db.isOpen()) { ClientEditor *clientEditorDlg = new ClientEditor(this); clientEditorDlg->setTitle("Add Customer"); ClientInfo info; QPixmap photo; if (clientEditorDlg->exec() ) { info.code = clientEditorDlg->getCode(); info.name = clientEditorDlg->getName(); info.address = clientEditorDlg->getAddress(); info.phone = clientEditorDlg->getPhone(); info.cell = clientEditorDlg->getCell(); photo = clientEditorDlg->getPhoto(); info.points = clientEditorDlg->getPoints(); info.discount = clientEditorDlg->getDiscount(); info.since = QDate::currentDate(); info.photo = Misc::pixmap2ByteArray(new QPixmap(photo)); if (!db.isOpen()) db.open(); if (!myDb->insertClient(info)) qDebug()<<myDb->lastError(); //Select the new client and update info. if ( specialOrders.isEmpty() ) { clientsHash = myDb->getClientsHash(); //refresh clients with this new info. clientInfo = info; //update the client. updateClientInfo(); refreshTotalLabel(); } else { qDebug()<<"Cannot change customer while using Special Orders"; ui_mainview.editClient->clear(); } } delete clientEditorDlg; } delete myDb; ui_mainview.editItemCode->setFocus(); setupGridView(); } void iotposView::showCreditPayment() { if (ui_mainview.creditPaymentWidget->isVisible()) { //if payment widget is already visible, then make the payment. doCreditPayment(); } else { //show the payment widget... QString clientCode = ui_mainview.editClientIdForCredit->text(); if (crInfo.id <= 0 || crClientInfo.id <= 0) return; //PLEASE ENTER CLIENT CODE FIRST!!! ui_mainview.creditPaymentWidget->show(); ui_mainview.editCreditTendered->setFocus(); } } void iotposView::tenderedChanged() { if (crInfo.id <= 0 || crClientInfo.id <= 0) return; //PLEASE ENTER CLIENT CODE FIRST!!! double tendered = ui_mainview.editCreditTendered->text().toDouble(); double change = 0; if (crInfo.total <= 0) change = 0; //no change, since no +credit. else change = tendered - crInfo.total; if ( crInfo.total > tendered ) { change = 0; ui_mainview.btnPayCredit->setText(i18n("Make partial payment")); } else if ( tendered > crInfo.total ) { ui_mainview.btnPayCredit->setText(i18n("Pay")); } ui_mainview.lblCreditChange->setText(KGlobal::locale()->formatMoney(change)); } void iotposView::doCreditPayment() { if (crClientInfo.id <= 0 || crInfo.id <= 0) return; //need a client and credit first. double change = 0; double tendered = ui_mainview.editCreditTendered->text().toDouble(); if (tendered <= 0) { ui_mainview.editCreditTendered->setFocus(); ui_mainview.editCreditTendered->shake(); return; //no tendered amount! } if (crInfo.total <= 0) change = 0; //no change, since no +credit. else change = tendered - crInfo.total; //Keep change when desired by client OR when credit is CERO or NEGATIVE, this means that the client wants to deposit to have debit. bool keepChange = (ui_mainview.chKeepDebit->isChecked() || crInfo.total <= 0 ); qDebug()<<__FUNCTION__<<" :: Tendered:"<<tendered<<" Change:"<<change<<" KeepChange:"<<keepChange; Azahar *myDb = new Azahar; myDb->setDatabase(db); //We have just one creditInfo for each client, the total is the +/- credit/debit. //We must create one credit_history for the payment. CreditHistoryInfo crHistory; crHistory.customerId = crClientInfo.id; crHistory.date = QDate::currentDate(); crHistory.time = QTime::currentTime(); crHistory.saleId = 0; //This is not a sale, its a payment, so we set saleId to 0 to identify it is a payment. crHistory.amount = 0; //reset this first... double cIn = 0; if (keepChange && change > 0) { crHistory.amount = -tendered; //pay the total, and let the change as debit (-). CHANGE is POSITIVE and will be the amount debited. crInfo.total -= tendered;//it includes change. and tendered is the amount to decrement the credit due to payment. cIn = tendered; qDebug()<<" CASE 1 | final results: cr.total:"<<crInfo.total<<" crHistory.amount:"<<crHistory.amount<<" Tendered:"<<tendered; } else if (!keepChange && change > 0) { crInfo.total -= (tendered - change); //paying the total credit. it is the same as assigning 0 crHistory.amount = -(tendered - change); //just pay the total and give the change to the client. cIn = tendered - change; //positive qDebug()<<" CASE 2 | final results: *(should be 0) cr.total:"<<crInfo.total<<" crHistory.amount:"<<crHistory.amount<<" Tendered:"<<tendered; } else if ( change <= 0 ) { crHistory.amount = -tendered; // Just make a partial payment. change is 0 or less. crInfo.total -= tendered; //no change, and partial payment cIn = tendered; qDebug()<<" CASE 3 | final results: cr.total:"<<crInfo.total<<" crHistory.amount:"<<crHistory.amount<<" Tendered:"<<tendered; } myDb->insertCreditHistory( crHistory ); myDb->updateCredit( crInfo ); insertCashInForCredit( crInfo, cIn ); qDebug()<<"Credit remaining:"<<crInfo.total<<" Payment:"<<crHistory.amount<<" Change:"<<change; //ui_mainview.creditPaymentWidget->hide(); //ui_mainview.editClientIdForCredit->clear(); ui_mainview.editCreditTendered->clear(); //print ticket. NOTE: This prints the credit report.. We want to print the NEW PAYMENT ALSO, so add to the document. calculateTotalForClient(); //Small change by Shane Rees to bring up a message box before printing after partial payments QMessageBox::StandardButton reply; reply = QMessageBox::question(this, "Print payment ticket", "Do you wish to print partial payment ticket?", QMessageBox::Yes|QMessageBox::No); if(reply == QMessageBox::Yes){ qDebug() << "Printing partial ticket"; printCreditReport(); } else{ qDebug() << "Skipping partial ticket printing"; } //close db and credit dialog, delaying a bit. //QTimer::singleShot(3000, creditPanel, SLOT(hidePanel())); delete myDb; } void iotposView::printCreditReport() { if (Settings::printTicket()) { if (Settings::smallTicketCUPS()) { QPrinter printer(QPrinter::HighResolution); printer.setFullPage( true ); printer.setPageMargins(0,0,0,0,QPrinter::Millimeter); qDebug()<<"-Paper Width: "<<printer.widthMM()<<"mm"<<"; Page Width: "<<printer.width(); //NOTE: I dont know why the printer reports a paper width of 210mm (that is a A4/Letter width). // Why, why?.. even the default printer is the TSP800. if (printer.widthMM() > 150) printer.setPaperSize(QSizeF(104,110), QPrinter::Millimeter); // Resetting to 104mm (4 inches) paper. qDebug()<<"+Paper Width: "<<printer.widthMM()<<"mm"<<"; Page Width: "<<printer.width(); ui_mainview.creditContent->print(&printer); //this prints directly to the default printer. No print dialog. //if export to pdf QString fn = QString("%1/iotpos-printing/").arg(QDir::homePath()); QDir dir; if (!dir.exists(fn)) dir.mkdir(fn); fn = fn+QString("credit-%1__%2.pdf").arg(crClientInfo.code).arg(QDate::currentDate().toString("dd-MMM-yy")); qDebug()<<" Exporting credit report to:"<<fn; printer.setOutputFileName(fn); printer.setOutputFormat(QPrinter::PdfFormat); printer.setPageMargins(0,0,0,0,QPrinter::Millimeter); printer.setPaperSize(QSizeF(72,200), QPrinter::Millimeter); ui_mainview.creditContent->print(&printer); } else if (Settings::printZeroTicket()) { // Send to spool file QPrinter printer(QPrinter::HighResolution); printer.setFullPage( true ); printer.setPageMargins(0,0,0,0,QPrinter::Millimeter); qDebug()<<"-Paper Widt: "<<printer.widthMM()<<"mm"<<"; Page Widt: "<<printer.width(); ui_mainview.creditContent->print(&printer); } else { // this will send internal credit to default printer ig // print button is clicked // TODO: GET DIALOG BOX UP. QPrinter printer(QPrinter::HighResolution); printer.setFullPage( true ); printer.setPageMargins(0,0,0,0,QPrinter::Millimeter); qDebug()<<"-Paper Widt: "<<printer.widthMM()<<"mm"<<"; Page Widt: "<<printer.width(); ui_mainview.creditContent->print(&printer); } } else { } } void iotposView::insertCashInForCredit(const CreditInfo &credit, const double &amount) { Azahar *myDb = new Azahar; myDb->setDatabase(db); CashFlowInfo info; info.amount = amount; info.reason = i18n("Payment for Credit %1", credit.id); info.date = QDate::currentDate(); info.time = QTime::currentTime(); info.terminalNum = Settings::editTerminalNumber(); info.userid = loggedUserId; info.type = ctCashInCreditPayment; qulonglong cfId = myDb->insertCashFlow(info); //affect drawer //NOTE: What about CUPS printers? if (Settings::openDrawer() && Settings::smallTicketDotMatrix() && Settings::printTicket() ) drawer->open(); drawer->addCash(info.amount); drawer->insertCashflow(cfId); QString authBy = loggedUserName; log(loggedUserId, QDate::currentDate(), QTime::currentTime(), i18n("Cash-IN-CreditPayment [%1] for credit %5 by %2 at terminal %3 on %4",QString::number(info.amount, 'f',2),authBy,Settings::editTerminalNumber(),QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm"), credit.id)); delete myDb; } ///http://cartan.cas.suffolk.edu/qtdocs/demos-textedit-textedit-cpp.html void iotposView::calculateTotalForClient() { ui_mainview.creditContent->clear(); if (crClientInfo.id > 0) { Azahar *myDb = new Azahar; myDb->setDatabase(db); //TODO: Limit the credit History result, to the last ones (5?) and paid/unpaid? QList<CreditHistoryInfo> creditHistory = myDb->getCreditHistoryForClient(crClientInfo.id, 30); //limit last 30 days credits. //print client info. ///Use QTextDocument via QTextEdit QTextCursor cursor(ui_mainview.creditContent->textCursor()); cursor.movePosition(QTextCursor::Start); QTextFrame *topFrame = cursor.currentFrame(); QTextFrameFormat topFrameFormat = topFrame->frameFormat(); topFrameFormat.setPadding(5); topFrame->setFrameFormat(topFrameFormat); QTextCharFormat textFormat; QTextCharFormat smTextFormat; QTextCharFormat boldFormat; QTextCharFormat italicsFormat; QTextCharFormat titleFormat; QTextCharFormat hdrFormat; QTextBlockFormat blockCenter; QTextBlockFormat blockLeft; QTextBlockFormat blockRight; boldFormat.setFontWeight(QFont::Bold); boldFormat.setFontPointSize(8); italicsFormat.setFontPointSize(8); textFormat.setFontPointSize(8); smTextFormat.setFontPointSize(7); smTextFormat.setFontItalic(true); italicsFormat.setFontItalic(true); titleFormat.setFontPointSize(15); titleFormat.setFontItalic(true); titleFormat.setFontWeight(QFont::Bold); hdrFormat = boldFormat; hdrFormat.setFontUnderline(true); blockCenter.setAlignment(Qt::AlignHCenter); blockLeft.setAlignment(Qt::AlignLeft); blockRight.setAlignment(Qt::AlignRight); //title cursor.setBlockFormat(blockCenter); cursor.insertText(i18n("CREDIT REPORT"), titleFormat); cursor.insertBlock(); cursor.insertText(KGlobal::locale()->formatDateTime(QDateTime::currentDateTime(), KLocale::LongDate), textFormat); cursor.insertBlock(); cursor.insertBlock(); italicsFormat.setFontPointSize(13); cursor.insertText(crClientInfo.name, italicsFormat); cursor.insertBlock(); //cursor.setPosition(topFrame->lastPosition()); cursor.setBlockFormat(blockCenter); italicsFormat.setFontPointSize(8); cursor.insertText(i18n("Balance: %1", KGlobal::locale()->formatMoney(crInfo.total)), boldFormat); cursor.insertBlock(); cursor.insertBlock(); qDebug()<<__FUNCTION__<<"Credit for "<<crInfo.clientId<<" -- $"<<crInfo.total; QTextTableFormat itemsTableFormat; itemsTableFormat.setAlignment(Qt::AlignHCenter); itemsTableFormat.setWidth(QTextLength(QTextLength::PercentageLength, 100)); QTextTable *itemsTable; QTextFrameFormat itemsFrameFormat; if (!creditHistory.isEmpty()) { //check if there is any credit entry for TODAY. int todayNum = 0; //I dont like to iterate each credit to know that there is one. foreach(CreditHistoryInfo credit, creditHistory){ if (credit.date == QDate::currentDate() ) { todayNum++; break; //finish here, with only one we need to print it. } } itemsTable = cursor.insertTable(1, 3, itemsTableFormat); //table itemsFrameFormat = cursor.currentFrame()->frameFormat(); itemsFrameFormat.setBorder(0); itemsFrameFormat.setPadding(1); cursor.currentFrame()->setFrameFormat(itemsFrameFormat); cursor = itemsTable->cellAt(0, 0).firstCursorPosition(); cursor.insertText(i18n("Date"), hdrFormat); //NOTE: It is not really needed to include the date in TODAY history. cursor = itemsTable->cellAt(0, 1).firstCursorPosition(); cursor.insertText(i18n("Amount"), hdrFormat); cursor = itemsTable->cellAt(0, 2).firstCursorPosition(); cursor.insertText(i18n("Sale #"), hdrFormat); if (todayNum > 0) { foreach(CreditHistoryInfo credit, creditHistory){ if (credit.date == QDate::currentDate() ) { int row = itemsTable->rows(); itemsTable->insertRows(row, 1); cursor = itemsTable->cellAt(row, 0).firstCursorPosition(); cursor.insertText(KGlobal::locale()->formatDate(credit.date, KLocale::ShortDate), boldFormat); cursor = itemsTable->cellAt(row, 1).firstCursorPosition(); cursor.insertText(KGlobal::locale()->formatMoney(credit.amount), boldFormat); cursor = itemsTable->cellAt(row, 2).firstCursorPosition(); if (credit.saleId == 0) cursor.insertText(i18n("Payment"), textFormat); else cursor.insertText(QString::number(credit.saleId), textFormat); } } } //any today entry? //Beyond today... cursor.movePosition(QTextCursor::NextBlock); itemsTableFormat.setAlignment(Qt::AlignHCenter); itemsTableFormat.setWidth(QTextLength(QTextLength::PercentageLength, 100)); foreach(CreditHistoryInfo credit, creditHistory){ if (credit.date != QDate::currentDate() ) { int row = itemsTable->rows(); itemsTable->insertRows(row, 1); cursor = itemsTable->cellAt(row, 0).firstCursorPosition(); cursor.insertText(KGlobal::locale()->formatDate(credit.date, KLocale::ShortDate), boldFormat); cursor = itemsTable->cellAt(row, 1).firstCursorPosition(); cursor.insertText(KGlobal::locale()->formatMoney(credit.amount), boldFormat); cursor = itemsTable->cellAt(row, 2).firstCursorPosition(); if (credit.saleId == 0) cursor.insertText(i18n("Payment"), textFormat); else cursor.insertText(QString::number(credit.saleId), textFormat); } } } //if not empty creditHistory delete myDb; } ui_mainview.creditContent->setReadOnly(true); } BasketPriceSummary iotposView::recalculateBasket(double oDiscountMoney) { BasketPriceCalculationService basketPriceCalculationService; BasketPriceSummary summary = basketPriceCalculationService.calculateBasketPrice(this->productsHash, this->clientInfo, oDiscountMoney); summary.getPoints(); this->subTotalSum = summary.getNet().toDouble(); this->totalSumWODisc = summary.getGross().toDouble(); this->totalSum = summary.getGross().toDouble(); this->totalTax = summary.getTax().toDouble(); this->discMoney = summary.getDiscountGross().toDouble(); // this->buyPoints = (qulonglong)summary.getPoints(); QString points = QString::number(summary.getPoints()); qDebug() << "[recalculateBasket] net: " << summary.getNet() << ", gross: " << summary.getGross() << ", discount: " << summary.getDiscountGross() << ", tax: " << summary.getTax() << ", points: " << points; return summary; } #include "iotposview.moc" void iotposView::on_rbFilterByCategory_clicked() { ui_mainview.editItemCode->clear(); ui_mainview.frameGridView->show(); } void iotposView::on_rbFilterByPopularity_clicked() { ui_mainview.editItemCode->clear(); }
287,553
C++
.cpp
6,003
41.575546
606
0.665481
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
752,808
soselector.cpp
hiramvillarreal_iotpos/src/soselector.cpp
/*************************************************************************** * Copyright (C) 2013-2015 by Hiram R. Villarreal * * hiramvillarreal.ap@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include <KLocale> #include <KMessageBox> #include <QByteArray> #include <QRegExpValidator> #include <QRegExp> #include <QtSql> #include "soselector.h" #include "../dataAccess/azahar.h" SOSelectorUI::SOSelectorUI( QWidget *parent ) : QFrame( parent ) { setupUi( this ); } SOSelector::SOSelector( QWidget *parent ) : KDialog( parent ) { m_modelAssigned = false; ticketNumber = 0; ui = new SOSelectorUI( this ); setMainWidget( ui ); setCaption( i18n("Special Orders") ); setButtons( KDialog::Ok|KDialog::Cancel ); enableButtonOk(false); QRegExp regexpC("[0-9]{0,13}"); QRegExpValidator * validatorEAN13 = new QRegExpValidator(regexpC, this); ui->editSaleId->setValidator(validatorEAN13); connect( ui->editName, SIGNAL(textEdited( const QString &)), SLOT(applyFilter()) ); connect( ui->editSaleId, SIGNAL(textEdited( const QString &)), SLOT(applyFilter()) ); connect( ui->editSaleId, SIGNAL(returnPressed()), SLOT(selectItem()) ); connect( ui->rbAll, SIGNAL(toggled(bool)), SLOT(applyFilter()) ); connect( ui->rbDate, SIGNAL(toggled(bool)), SLOT(applyFilter()) ); connect( ui->rbName, SIGNAL(toggled(bool)), SLOT(applyFilter()) ); connect( ui->rbSaleId, SIGNAL(toggled(bool)), SLOT(applyFilter()) ); //connect( ui->tableWidget, SIGNAL(activated(const QModelIndex &)), SLOT(itemClicked(const QModelIndex &)) ); connect( ui->tableWidget, SIGNAL(clicked(const QModelIndex &)), SLOT(itemClicked(const QModelIndex &)) ); setDefaultButton(KDialog::Ok); ui->datePicker->setDate(QDate::currentDate()); } void SOSelector::selectItem() { enableButtonOk(false); QModelIndex index = ui->tableWidget->currentIndex(); if (index == soModel->index(-1,-1) ) { if (soModel->rowCount() == 1) { ui->tableWidget->selectRow(0); index = ui->tableWidget->currentIndex(); enableButtonOk(true); //qDebug()<<"only one row, selecting:"<<soModel->record(index.row()).value("saleid").toULongLong(); } else { //Que hacer? seleccionar la primera, no seleccionar nada? enableButtonOk(false); //let the user select the appropiate. } } ticketNumber = soModel->record(index.row()).value("saleid").toULongLong(); //qDebug()<<"Selected ticket# "<<ticketNumber; } void SOSelector::itemClicked(const QModelIndex &index) { enableButtonOk(false); ticketNumber = soModel->record(index.row()).value("saleid").toULongLong(); Azahar *myDb = new Azahar; myDb->setDatabase(db); int count = myDb->getReadySOCountforSale(ticketNumber); if (count > 0) { //ok, the tr. contains at least one so not-delivered and not cancelled. enableButtonOk(true); } //qDebug()<<"Clicked on ticket# "<<ticketNumber<<" #"<<count; delete myDb; } void SOSelector::applyFilter() { if (ui->rbName->isChecked()) { //by name QString text = ui->editName->text(); QRegExp regexp = QRegExp(text); if ( !regexp.isValid() ) { ui->editName->setText(""); text="";} if (text == "*" || text == "") soModel->setFilter("status > 0 and status < 3"); else soModel->setFilter(QString("status > 0 and status < 3 and name REGEXP '%1'").arg(text)); } else if (ui->rbDate->isChecked()){ // by date QDate d = ui->datePicker->date(); QDateTime dt = QDateTime(d); QString dtStr = dt.toString("yyyy-MM-dd hh:mm:ss"); QString dtStr2= d.toString("yyyy-MM-dd")+" 23:59:59"; soModel->setFilter(QString("dateTime>='%1' and dateTime<='%2' AND status > 0 and status < 3").arg(dtStr).arg(dtStr2)); } else if (ui->rbSaleId->isChecked()){ //by ticket number if (ui->editSaleId->text().isEmpty()) soModel->setFilter("status > 0 and status < 3"); else { QString num = ui->editSaleId->text(); soModel->setFilter(QString("saleid=%1 AND status > 0 and status < 3").arg(num)); } } else { //All soModel->setFilter("status > 0 and status < 3"); //saleid in (select id from transactions where state=2) } ///NOTE: Due to limitations on QSQLTableModel, we cannot use the GROUP BY statement on the model. /// This only can be used on non-relational models, so we can consider to not use the relational one. // GROUP BY special_orders.saleid DESC ///NOTE: I can bypass this by setting a '1=1 GROUP BY...' and not setting the 'setRelation'.. but the /// Value for STATUS will be numbers. I found a way - a hack - of accomplish this perfectly: /// Simply creating a VIEW on the Database, grouped by saleid, so i dont need the 'GROUP BY..' clause /// here in the model. soModel->setSort(8, Qt::DescendingOrder); soModel->select(); //qDebug()<<"Query:"<<soModel->query().lastQuery(); } void SOSelector::setupModel() { soModel = new QSqlRelationalTableModel(); soModel->setTable("v_groupedSO"); int soIdIndex = soModel->fieldIndex("orderid"); int soDateIndex = soModel->fieldIndex("dateTime"); int soNameIndex= soModel->fieldIndex("name"); int soStatusIndex = soModel->fieldIndex("status"); int soSaleIdIndex= soModel->fieldIndex("saleid"); int soGroupElemIndex= soModel->fieldIndex("groupElements"); int soQtyIndex = soModel->fieldIndex("qty"); int soPriceIndex= soModel->fieldIndex("price"); int soCostIndex= soModel->fieldIndex("cost"); int soUnitsIndex= soModel->fieldIndex("units"); int soNotesIndex=soModel->fieldIndex("notes"); int soPaymentIndex=soModel->fieldIndex("payment"); int soCompletePaymentIndex=soModel->fieldIndex("completePayment"); soModel->setHeaderData(soIdIndex, Qt::Horizontal, i18n("Order #")); soModel->setHeaderData(soNameIndex, Qt::Horizontal, i18n("Name")); soModel->setHeaderData(soDateIndex, Qt::Horizontal, i18n("Date") ); soModel->setHeaderData(soStatusIndex, Qt::Horizontal, i18n("Status") ); soModel->setHeaderData(soSaleIdIndex, Qt::Horizontal, i18n("Tr. Id") ); soModel->setRelation(soStatusIndex, QSqlRelation("so_status", "id", "text")); ui->tableWidget->setModel(soModel); ui->tableWidget->setColumnHidden(soGroupElemIndex, true); ui->tableWidget->setColumnHidden(soQtyIndex, true); ui->tableWidget->setColumnHidden(soPriceIndex, true); ui->tableWidget->setColumnHidden(soCostIndex, true); ui->tableWidget->setColumnHidden(soUnitsIndex, true); ui->tableWidget->setColumnHidden(soNotesIndex, true); ui->tableWidget->setColumnHidden(soPaymentIndex, true); ui->tableWidget->setColumnHidden(soCompletePaymentIndex, true); ui->tableWidget->setColumnHidden(soDateIndex, true); ui->tableWidget->setColumnHidden(soIdIndex, true); ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers); ui->tableWidget->setSelectionMode(QAbstractItemView::SingleSelection); m_modelAssigned = true; //Show only ready for completion orders (status >0 and <3) soModel->setFilter("status > 0 and status < 3"); soModel->setSort(8, Qt::DescendingOrder); soModel->select(); ui->tableWidget->resizeRowsToContents(); ui->tableWidget->resizeColumnsToContents(); //changed here because when assigning the date to the datePicker this signal was causing to apply the filter which caused a crash due to that at such time the model was not set up. connect( ui->datePicker, SIGNAL(changed(QDate)), SLOT(applyFilter()) ); } void SOSelector::setDb(QSqlDatabase database) { db = database; if (!db.isOpen()) db.open(); //wait and create model QTimer::singleShot(200, this, SLOT(setupModel())); } SOSelector::~SOSelector() { delete ui; } void SOSelector::slotButtonClicked(int button) { if (button == KDialog::Ok) { QDialog::accept(); } else QDialog::reject(); }
9,104
C++
.cpp
195
43.220513
182
0.659258
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
752,809
resume.cpp
hiramvillarreal_iotpos/src/resume.cpp
/*************************************************************************** * Copyright (C) 2013-2015 by Hiram R. Villarreal * * hiramvillarreal.ap@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include <KLocale> #include <KMessageBox> #include <QByteArray> #include <QRegExpValidator> #include <QRegExp> #include <QtSql> #include "resume.h" #include "../dataAccess/azahar.h" ResumeDialogUI::ResumeDialogUI( QWidget *parent ) : QFrame( parent ) { setupUi( this ); } ResumeDialog::ResumeDialog( QWidget *parent ) : KDialog( parent ) { m_modelAssigned = false; trNumber = 0; userId = 0; ui = new ResumeDialogUI( this ); setMainWidget( ui ); setCaption( i18n("Resume Sale") ); setButtons( KDialog::Ok|KDialog::Cancel ); enableButtonOk(false); connect(ui->tableWidget, SIGNAL(clicked(const QModelIndex &)), SLOT(itemClicked(const QModelIndex &))); connect( ui->editSearch, SIGNAL(returnPressed()), SLOT(filterClient()) ); setDefaultButton(KDialog::Ok); } void ResumeDialog::selectItem() { enableButtonOk(false); QModelIndex index = ui->tableWidget->currentIndex(); if (index == trModel->index(-1,-1) ) { if (trModel->rowCount() == 1) { ui->tableWidget->selectRow(0); index = ui->tableWidget->currentIndex(); enableButtonOk(true); } else { enableButtonOk(false); //let the user select the appropiate. } } trNumber = trModel->record(index.row()).value("id").toULongLong(); qDebug()<<"Selected tr # "<<trNumber; } void ResumeDialog::itemClicked(const QModelIndex &index) { enableButtonOk(false); ui->contentTable->clearContents(); ui->contentTable->setRowCount(0); pList.clear(); soList.clear(); trNumber = trModel->record(index.row()).value("id").toULongLong(); qDebug()<<"==> selected ticket number:"<<trNumber; Azahar *myDb = new Azahar; myDb->setDatabase(db); TransactionInfo tInfo = myDb->getTransactionInfo(trNumber); clientId = tInfo.clientid; trDate = tInfo.date; trTime = tInfo.time; QStringList _pList = tInfo.itemlist.split(","); QStringList _soList= tInfo.specialOrders.split(","); int count = 0; //first iterate each product/group foreach(QString str, _pList) { qulonglong code = str.section('/',0,0).toULongLong(); double qty = str.section('/',1,1).toDouble(); if (code <= 0 ) break; count++; ProductInfo pInfo = myDb->getProductInfo(QString::number(code)); pInfo.qtyOnList = qty; pList << pInfo; //NOTE:Check for product Availability ?? //insert to the cntent table int rowCount = ui->contentTable->rowCount(); ui->contentTable->insertRow(rowCount); ui->contentTable->setItem(rowCount, 0, new QTableWidgetItem(QString::number(qty))); ui->contentTable->setItem(rowCount, 1, new QTableWidgetItem(pInfo.desc)); } //now iterate each special order foreach(QString str, _soList) { qulonglong code = str.section('/',0,0).toULongLong(); double qty = str.section('/',1,1).toDouble(); if (code <= 0 ) break; count++; SpecialOrderInfo soInfo = myDb->getSpecialOrderInfo(code); soList << soInfo; //NOTE:Check for product Availability ?? //insert to the content table int rowCount = ui->contentTable->rowCount(); ui->contentTable->insertRow(rowCount); ui->contentTable->setItem(rowCount, 0, new QTableWidgetItem(QString::number(qty))); ui->contentTable->setItem(rowCount, 1, new QTableWidgetItem(soInfo.name)); } qDebug()<<"Clicked on tr# "<<trNumber<<" items count:"<<count; if ( trNumber > 0 && count > 0 ) enableButtonOk(true); delete myDb; ui->contentTable->resizeRowsToContents(); ui->contentTable->resizeColumnsToContents(); } void ResumeDialog::item_Clicked(const QModelIndex &index, const QModelIndex &indexp) { itemClicked(index); } void ResumeDialog::setupModel() { trModel = new QSqlRelationalTableModel(); trModel->setTable("v_transS"); int trIdIndex = trModel->fieldIndex("id"); int trDateIndex = trModel->fieldIndex("date"); int trTimeIndex= trModel->fieldIndex("time"); int trStateIndex = trModel->fieldIndex("state"); int trUserIndex= trModel->fieldIndex("userid"); int trClientIndex= trModel->fieldIndex("clientid"); int trItemsIndex = trModel->fieldIndex("itemslist"); int trTerminalNumIndex= trModel->fieldIndex("terminalnum"); int trItemCountIndex= trModel->fieldIndex("itemcount"); trModel->setHeaderData(trIdIndex, Qt::Horizontal, i18n("Tr. #")); trModel->setHeaderData(trTimeIndex, Qt::Horizontal, i18n("Time")); trModel->setHeaderData(trDateIndex, Qt::Horizontal, i18n("Date") ); trModel->setHeaderData(trTerminalNumIndex, Qt::Horizontal, i18n("Terminal")); trModel->setHeaderData(trClientIndex, Qt::Horizontal, i18n("Client")); trModel->setRelation(trClientIndex, QSqlRelation("clients", "id", "name")); ui->tableWidget->setModel(trModel); ui->tableWidget->setColumnHidden(trStateIndex, true); ui->tableWidget->setColumnHidden(trUserIndex, true); ui->tableWidget->setColumnHidden(trItemsIndex, true); ui->tableWidget->setColumnHidden(trItemCountIndex, true); ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers); ui->tableWidget->setSelectionMode(QAbstractItemView::SingleSelection); m_modelAssigned = true; //NOTE: we need to know the userid before this method! So setUserId() method must be called before setDb() trModel->setFilter(QString("userid = %1").arg(userId)); trModel->setSort(0, Qt::DescendingOrder); trModel->select(); ui->tableWidget->resizeRowsToContents(); ui->tableWidget->resizeColumnsToContents(); qDebug()<<"SetupModel done..."; //connecting the signal for updating the transaction items. QItemSelectionModel *selModel = ui->tableWidget->selectionModel(); connect(selModel, SIGNAL(currentRowChanged(const QModelIndex &, const QModelIndex &)), SLOT(item_Clicked(const QModelIndex &, const QModelIndex &))); } void ResumeDialog::setDb(QSqlDatabase database) { db = database; if (!db.isOpen()) db.open(); //wait and create model QTimer::singleShot(300, this, SLOT(setupModel())); } ResumeDialog::~ResumeDialog() { delete ui; } void ResumeDialog::slotButtonClicked(int button) { if (button == KDialog::Ok) { QDialog::accept(); } else QDialog::reject(); } void ResumeDialog::filterClient() { QString str = ui->editSearch->text(); //analize string, if it is a number, then search by id, if alphanum then by name. if (str.isEmpty() || str == " "){ //clean filter trModel->setFilter(""); trModel->setSort(0, Qt::DescendingOrder); trModel->select(); } else { //search by client code (alphanum, 0000001 and not 1) //int trDateIndex = trModel->fieldIndex("date"); trModel->setFilter(QString("code = '%1'").arg(str)); //userid = %1 .arg(userId) trModel->setSort(/*trDateIndex*/0, Qt::DescendingOrder); //it can be sorted only by one field. trModel->select(); //clean edit after filtering? This can be faster to make search one after another if needed. ui->editSearch->clear(); } }
8,419
C++
.cpp
199
38.668342
108
0.655838
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
752,810
ticketpopup.cpp
hiramvillarreal_iotpos/src/ticketpopup.cpp
/*************************************************************************** * Copyright (C) 2009 by Miguel Chavez Gamboa * * hiramvillarreal.ap@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "ticketpopup.h" #include <QtGui> #include <QTimer> #include <kstandarddirs.h> TicketPopup::TicketPopup(QString text, QPixmap pixmap, int timeToClose) { setWindowFlags(Qt::Dialog|Qt::FramelessWindowHint); setWindowModality(Qt::ApplicationModal); setObjectName("main"); gridLayout = new QGridLayout(this); imagelabel = new QLabel(this); imagelabel->setPixmap(pixmap); imagelabel->setAlignment(Qt::AlignCenter); gridLayout->addWidget(imagelabel, 0, 0); editText = new QTextEdit(this); editText->setHtml(text); editText->setReadOnly(true); gridLayout->addWidget(editText, 1, 0); gridLayout->setMargin(8); timer = new QTimer(this); timer->setInterval(timeToClose); connect(timer, SIGNAL(timeout()), this, SLOT(closeIt())); QString path = KStandardDirs::locate("appdata", "images/"); QString filen = path + "/imgPrint.png"; QPixmap pix(filen); setMask(pix.mask()); QString st; st = QString("main { background-image: url(%1);}").arg(filen); setStyleSheet(st); } void TicketPopup::popup() { //NOTE: Why before show() the frameGeometry is bigger, and after showing it, it resizes itself? move(2000,2000); show(); int x = (QApplication::desktop()->width()/2 )-(frameGeometry().width()/2); int y = (QApplication::desktop()->height()/2)-(frameGeometry().height()/2); if (y < 100){ setGeometry(x,0,340,250); } else { setGeometry(x,0,340,340); } timer->start(); } void TicketPopup::keyPressEvent( QKeyEvent * event) { if ( event->key() == Qt::Key_Escape ) { emit onTicketPopupClose(); timer->stop(); close(); } else QDialog::keyPressEvent(event); } void TicketPopup::paintEvent(QPaintEvent *e) { QPainter painter; painter.begin(this); painter.setClipRect(e->rect()); painter.setRenderHint(QPainter::Antialiasing); paint(&painter); painter.restore(); painter.save(); int level = 180; painter.setPen(QPen(QColor(level, level, level), 6)); painter.setBrush(Qt::NoBrush); painter.drawRect(rect()); } void TicketPopup::closeIt() { timer->stop(); emit onTicketPopupClose(); //to let iotstockview unfreeze the widgets close(); } #include "ticketpopup.moc"
3,622
C++
.cpp
93
36.505376
97
0.596356
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
752,811
misc.cpp
hiramvillarreal_iotpos/src/misc.cpp
/*************************************************************************** * Copyright (C) 2013-2015 by Hiram R. Villarreal * * hiramvillarreal.ap@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "misc.h" #include <QByteArray> #include <QBuffer> #include <QIODevice> #include <QPixmap> #include <QSize> #include <QFontMetrics> #include <QStringList> #include <QString> QByteArray Misc::pixmap2ByteArray(QPixmap *pix, bool scale) { QByteArray bytes; QBuffer buffer(&bytes); buffer.open(QIODevice::WriteOnly); int max = 150; if (((pix->height() > max) || (pix->width() > max)) && scale ) { QPixmap newPix; if (pix->height() == pix->width()) { newPix = pix->scaled(QSize(max, max)); } else if (pix->height() > pix->width() ) { newPix = pix->scaledToHeight(max); } else { newPix = pix->scaledToWidth(max); } if (newPix.hasAlpha()) { newPix.save(&buffer, "PNG"); } else newPix.save(&buffer, "JPG"); } else { //NO scaling needed... if (pix->hasAlpha()) { pix->save(&buffer, "PNG"); } else pix->save(&buffer, "JPG"); } return bytes; } QByteArray Misc::pixmap2ByteArray(QPixmap *pix, int maxW, int maxH) { QByteArray bytes; QBuffer buffer(&bytes); buffer.open(QIODevice::WriteOnly); if ((pix->height() > maxH) || (pix->width() > maxW) ) { QPixmap newPix; if (pix->height() == pix->width()) { newPix = pix->scaled(QSize(maxW, maxH)); } else if (pix->height() > pix->width() ) { newPix = pix->scaledToHeight(maxH); } else { newPix = pix->scaledToWidth(maxW); } if (newPix.hasAlpha()) { newPix.save(&buffer, "PNG"); } else newPix.save(&buffer, "JPG"); } else { //NO scaling needed... if (pix->hasAlpha()) { pix->save(&buffer, "PNG"); } else pix->save(&buffer, "JPG"); } return bytes; } QStringList Misc::stringToParagraph(const QString &str, const QFontMetrics &fm, const double &maxL) { QStringList strList; QString strCopy = str; double strW = fm.size(Qt::TextExpandTabs | Qt::TextDontClip, str).width(); double realTrozos = strW / maxL; int trozos = realTrozos; double diff = (realTrozos - trozos); if (diff > 0.25 && trozos > 0) trozos += 1; int tamTrozo = 0; if (trozos > 0) { tamTrozo = (str.length()/trozos); } else { tamTrozo = str.length(); } QStringList otherList; for (int x = 1; x <= trozos; x++) { //we repeat for each trozo if (x*(tamTrozo-1) < strCopy.length()) strCopy.insert(x*(tamTrozo-1), "| "); //create a section } otherList = strCopy.split("|");//NOTE: Sacar esta linea del for? if (!otherList.isEmpty()) strList << otherList; if (trozos < 1) strList << str; //qDebug()<<"rm : Trozos:"<<trozos<<" tamTrozo:"<<tamTrozo<<" realTrozos:"<<QString::number(realTrozos,'f', 2)<<" maxL:"<<maxL<<" str.width in pixels:"<<fm.size(Qt::TextExpandTabs | Qt::TextDontClip, str).width()<<" diff:"<<diff; return strList; } QStringList Misc::stringToParagraph(const QString &str, const int &maxChars) { QStringList strList; QString strCopy = str; double strLen = str.length(); double realTrozos = strLen / maxChars; int trozos = realTrozos; double diff = (realTrozos - trozos); if (diff > 0 && trozos > 0) trozos += 1; int tamTrozo = 0; if (trozos > 0) { tamTrozo = (str.length()/trozos); } else { tamTrozo = str.length(); } QStringList otherList; for (int x = 1; x <= trozos; x++) { //we repeat for each trozo if (x*(tamTrozo-1) < strCopy.length()) strCopy.insert(x*(tamTrozo-1), "|"); //create a section } otherList = strCopy.split("|"); //NOTE: Sacar esta linea del for? if (!otherList.isEmpty()) strList << otherList; if (trozos < 1) strList << str; //qDebug()<<"rm : Trozos:"<<trozos<<" tamTrozo:"<<tamTrozo<<" realTrozos:"<<QString::number(realTrozos,'f', 2)<<"Str Length: "<<str.length()<<" maxChars:"<<maxChars<<" diff:"<<diff; return strList; }
5,366
C++
.cpp
135
35.385185
233
0.558739
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
752,812
gaveta.cpp
hiramvillarreal_iotpos/src/gaveta.cpp
/*************************************************************************** * Copyright (C) 2013-2015 by Hiram R. Villarreal * * hiramvillarreal.ap@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ // #include <QString> #include <QDebug> #include <QDateTime> #include <QFile> #include <QProcess> #include "gaveta.h" Gaveta::Gaveta() { unused = true; totalTransactions = 0; setAvailableInCash(0.0); startDateTime = QDateTime::currentDateTime(); tIds.clear(); cashflowIds.clear(); } Gaveta::~Gaveta() { } void Gaveta::setPrinterDevice(QString file) { printerDevice = file; } void Gaveta::setInitialAmount(double qty) { initialAmount = qty; } //This is executed only when a new user is logged ( each startOperation() ) void Gaveta::setAvailableInCash(double amount) { reset(); availableInCash = amount; initialAmount = amount; if (amount>0) unused=false; else unused=true; } void Gaveta::reset() { availableInCash = 0; initialAmount = 0; setAvailableInCard(0.0); in = 0; out = 0; initialAmount = 0.0; cashTransactions = 0; cardTransactions = 0; totalTransactions = 0; tIds.clear(); cashflowIds.clear(); unused=true; } void Gaveta::setAvailableInCard(double amount) { availableInCard = amount; } void Gaveta::substractCash(double amount) { if (availableInCash < amount) qDebug()<<"WARNING: Available money in drawer is less than the amount to substract."; availableInCash -= amount; out += amount; } //This method is not congruent. Card Payments are done trough bank accounts, not physically. //This could be useful for cancel transactions paid with card. void Gaveta::substractCard(double amount) { qDebug()<<"Not implemented Gaveta::substractInCard:"<<amount; } void Gaveta::addCash(double amount) { availableInCash += amount; in += amount; } //This is only for informative tasks. To know how much money is got from certain transaction. void Gaveta::addCard(double amount) { availableInCard += amount; //Not increment in amount... because is not money physically in the drawer... } double Gaveta::getAvailableInCash() { return availableInCash; } double Gaveta::getAvailableInCard() { return availableInCard; } bool Gaveta::isUnused() { bool result = false; if (unused && (availableInCash==0) && (tIds.count()==0)) result = true; else result = false; return result; } void Gaveta::open() { QProcess process; // process.startDetached("sudo", QStringList() << "python" << "/home/pi/iotpos/py-thermal-printer-master/printer2.py"); process.startDetached("sudo", QStringList() << "python" << "/home/pi/iotpos/scripts/pulse.py"); QFile file(printerDevice); if (file.open(QIODevice::ReadWrite)) { qDebug()<<"Pinter | Openning drawer..."; QTextStream out(&file); out << "\x10\x14\x01\x00\x01"; // Pulse on pin 2 100 ms out << "\x10\x14\x01\x01\x01"; // Pulse on pin 5 100 ms QString msg = "\x10\x14\x01\x00\x01"; qint64 r = file.write( msg.toUtf8() ); qDebug()<<"bytes sent:"<<r; if (r == -1) { qDebug()<<"ERRROR Writing file.";} file.close(); } else qDebug()<<"ERROR: Could not open printer..."; } double Gaveta::getInitialAmount() { return initialAmount; } double Gaveta::getInAmount() { return in; } double Gaveta::getOutAmount() { return out; } void Gaveta::insertTransactionId(qulonglong id) { if (!tIds.contains(id)) tIds.append(id); } QList<qulonglong> Gaveta::getTransactionIds() { return tIds; } QList<qulonglong> Gaveta::getCashflowIds() { return cashflowIds; } void Gaveta::insertCashflow(qulonglong id) { if (!cashflowIds.contains(id)) cashflowIds.append(id); } void Gaveta::incCardTransactions() { cardTransactions += 1; totalTransactions +=1; } void Gaveta::incCashTransactions() { cashTransactions += 1; totalTransactions +=1; } int Gaveta::getCardTransactionsCount() { return cardTransactions; } int Gaveta::getCashTransactionsCount() { return cashTransactions; } int Gaveta::getTransactionsCount() { return totalTransactions; } void Gaveta::setStartDateTime(QDateTime datetime) { startDateTime = datetime; } QDateTime Gaveta::getStartDateTime() { return startDateTime; }
5,477
C++
.cpp
187
27.090909
122
0.64389
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
752,813
dialogclientdata.cpp
hiramvillarreal_iotpos/src/dialogclientdata.cpp
/*************************************************************************** * Copyright (C) 2012 by Miguel Chavez Gamboa * * hiramvillarreal.ap@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include <KLocale> #include <KMessageBox> #include <KFileDialog> #include <QByteArray> #include "dialogclientdata.h" DialogClientDataUI::DialogClientDataUI( QWidget *parent ) : QFrame( parent ) { setupUi( this ); } DialogClientData::DialogClientData( QWidget *parent ) : KDialog( parent ) { ui = new DialogClientDataUI( this ); setMainWidget( ui ); setCaption( i18n("Datos del Cliente") ); setButtons( KDialog::Ok/*|KDialog::Cancel */); setDefaultButton(KDialog::NoDefault); //disable default button (return Pressed) enableButton(KDialog::Ok, false); connect( ui->editNombre, SIGNAL(textEdited(const QString &)), SLOT(validate()) ); connect( ui->editRFC, SIGNAL(textEdited(const QString &)), SLOT(validate()) ); //TODO: Validar RFC. //QRegExp regexpName("[A-Za-z_0-9\\s\\\\/\\-]+");//any letter, number, both slashes, dash and lower dash. and any space //QRegExpValidator *regexpAlpha = new QRegExpValidator(regexpName, this); //ui->editRFC->setValidator(regexpAlpha); ui->editNombre->setFocus(); } DialogClientData::~DialogClientData() { delete ui; } void DialogClientData::validate() { bool valido = false; if ( !ui->editNombre->text().isEmpty() && !ui->editRFC->text().isEmpty()) valido = true; enableButton(KDialog::Ok, valido); } QString DialogClientData::getDireccion() { QString t = ui->editDireccion->toPlainText(); return t; } #include "dialogclientdata.moc"
2,939
C++
.cpp
63
43.698413
123
0.560336
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
752,814
saleqtydelegate.cpp
hiramvillarreal_iotpos/src/saleqtydelegate.cpp
#include <QtGui> #include "saleqtydelegate.h" #include "structs.h" #include "../dataAccess/azahar.h" SaleQtyDelegate::SaleQtyDelegate(QObject *parent) : QItemDelegate(parent) { } QWidget *SaleQtyDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &, const QModelIndex & index) const { if (index.column() == 1) { QSpinBox *editor = new QSpinBox(parent); ///We need to get the maximum, with stock level. Take into account the unlimited stock products. //get item data from db. Azahar *myDb = new Azahar; myDb->setDatabase(db); QModelIndex sibling = index.sibling( index.row(), 0 ); // colCode=0 qulonglong code = sibling.data(Qt::DisplayRole).toULongLong(); int stock = myDb->getProductStockQty( code ); //the spinbox only support integers. We need a config option to turn ON/OFF this feature. editor->setMinimum(1); editor->setMaximum(stock); //as the editor contains the actual data/0, and will change, then we set max to stockqty. delete myDb; return editor; } else { //I dont want to create editors on other fields. What/How to do this? editor=null? QLineEdit *editor = new QLineEdit(parent); editor->setReadOnly(true); return editor; } } void SaleQtyDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &) const { editor->setGeometry(option.rect); } void SaleQtyDelegate::setDb(QSqlDatabase database) { db = database; if (!db.isOpen()) db.open(); }
1,587
C++
.cpp
40
34.425
124
0.693056
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
752,815
sostatus.cpp
hiramvillarreal_iotpos/src/sostatus.cpp
/*************************************************************************** * Copyright (C) 2013-2015 by Hiram R. Villarreal * * hiramvillarreal.ap@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include <KLocale> #include <KMessageBox> #include <QByteArray> #include <QRegExpValidator> #include <QRegExp> #include <QtSql> #include "sostatus.h" #include "../dataAccess/azahar.h" SOStatusUI::SOStatusUI( QWidget *parent ) : QFrame( parent ) { setupUi( this ); } SOStatus::SOStatus( QWidget *parent ) : KDialog( parent ) { m_modelAssigned = false; ticketNumber = 0; ui = new SOStatusUI( this ); setMainWidget( ui ); setCaption( i18n("Change Status") ); setButtons( KDialog::Ok|KDialog::Cancel ); enableButtonOk(false); QRegExp regexpC("[0-9]{0,13}"); QRegExpValidator * validatorEAN13 = new QRegExpValidator(regexpC, this); ui->editSaleId->setValidator(validatorEAN13); connect( ui->editName, SIGNAL(textEdited( const QString &)), SLOT(applyFilter()) ); connect( ui->editSaleId, SIGNAL(textEdited( const QString &)), SLOT(applyFilter()) ); connect( ui->editSaleId, SIGNAL(returnPressed()), SLOT(selectItem()) ); connect( ui->rbAll, SIGNAL(toggled(bool)), SLOT(applyFilter()) ); connect( ui->rbDate, SIGNAL(toggled(bool)), SLOT(applyFilter()) ); connect( ui->rbName, SIGNAL(toggled(bool)), SLOT(applyFilter()) ); connect( ui->rbSaleId, SIGNAL(toggled(bool)), SLOT(applyFilter()) ); connect( ui->tableWidget, SIGNAL(clicked(const QModelIndex &)), SLOT(itemClicked(const QModelIndex &)) ); setDefaultButton(KDialog::Ok); ui->datePicker->setDate(QDate::currentDate()); } void SOStatus::selectItem() { enableButtonOk(false); QModelIndex index = ui->tableWidget->currentIndex(); if (index == soModel->index(-1,-1) ) { if (soModel->rowCount() == 1) { ui->tableWidget->selectRow(0); index = ui->tableWidget->currentIndex(); enableButtonOk(true); } else { enableButtonOk(false); //let the user select the appropiate. } } ticketNumber = soModel->record(index.row()).value("saleid").toULongLong(); //qDebug()<<"Selected ticket# "<<ticketNumber; } void SOStatus::itemClicked(const QModelIndex &index) { enableButtonOk(false); ticketNumber = soModel->record(index.row()).value("saleid").toULongLong(); Azahar *myDb = new Azahar; myDb->setDatabase(db); int count = myDb->getReadySOCountforSale(ticketNumber); if (count > 0) { //ok, the tr. contains at least one so not-delivered and not cancelled. enableButtonOk(true); } //qDebug()<<"Clicked on ticket# "<<ticketNumber<<" #"<<count; delete myDb; } void SOStatus::applyFilter() { if (ui->rbName->isChecked()) { //by name QString text = ui->editName->text(); QRegExp regexp = QRegExp(text); if ( !regexp.isValid() ) { ui->editName->setText(""); text="";} if (text == "*" || text == "") soModel->setFilter("status < 3"); else soModel->setFilter(QString("status < 3 and name REGEXP '%1'").arg(text)); } else if (ui->rbDate->isChecked()){ // by date QDate d = ui->datePicker->date(); QDateTime dt = QDateTime(d); QString dtStr = dt.toString("yyyy-MM-dd hh:mm:ss"); QString dtStr2= d.toString("yyyy-MM-dd")+" 23:59:59"; soModel->setFilter(QString("dateTime>='%1' and dateTime<='%2' AND status < 3").arg(dtStr).arg(dtStr2)); } else if (ui->rbSaleId->isChecked()){ //by ticket number if (ui->editSaleId->text().isEmpty()) soModel->setFilter(""); else { QString num = ui->editSaleId->text(); soModel->setFilter(QString("saleid=%1 AND status < 3").arg(num)); } } else { //All soModel->setFilter(""); } ///NOTE: Due to limitations on QSQLTableModel, we cannot use the GROUP BY statement on the model. /// This only can be used on non-relational models, so we can consider to not use the relational one. // GROUP BY special_orders.saleid DESC ///NOTE: I can bypass this by setting a '1=1 GROUP BY...' and not setting the 'setRelation'.. but the /// Value for STATUS will be numbers. I found a way - a hack - of accomplish this perfectly: /// Simply creating a VIEW on the Database, grouped by saleid, so i dont need the 'GROUP BY..' clause /// here in the model. soModel->setSort(8, Qt::DescendingOrder); soModel->select(); //qDebug()<<"Query:"<<soModel->query().lastQuery(); } void SOStatus::setupModel() { soModel = new QSqlRelationalTableModel(); soModel->setTable("v_groupedSO"); int soIdIndex = soModel->fieldIndex("orderid"); int soDateIndex = soModel->fieldIndex("dateTime"); int soNameIndex= soModel->fieldIndex("name"); int soStatusIndex = soModel->fieldIndex("status"); int soSaleIdIndex= soModel->fieldIndex("saleid"); int soGroupElemIndex= soModel->fieldIndex("groupElements"); int soQtyIndex = soModel->fieldIndex("qty"); int soPriceIndex= soModel->fieldIndex("price"); int soCostIndex= soModel->fieldIndex("cost"); int soUnitsIndex= soModel->fieldIndex("units"); int soNotesIndex=soModel->fieldIndex("notes"); int soPaymentIndex=soModel->fieldIndex("payment"); int soCompletePaymentIndex=soModel->fieldIndex("completePayment"); soModel->setHeaderData(soIdIndex, Qt::Horizontal, i18n("Order #")); soModel->setHeaderData(soNameIndex, Qt::Horizontal, i18n("Name")); soModel->setHeaderData(soDateIndex, Qt::Horizontal, i18n("Date") ); soModel->setHeaderData(soStatusIndex, Qt::Horizontal, i18n("Status") ); soModel->setHeaderData(soSaleIdIndex, Qt::Horizontal, i18n("Tr. Id") ); soModel->setRelation(soStatusIndex, QSqlRelation("so_status", "id", "text")); ui->tableWidget->setModel(soModel); ui->tableWidget->setColumnHidden(soGroupElemIndex, true); ui->tableWidget->setColumnHidden(soQtyIndex, true); ui->tableWidget->setColumnHidden(soPriceIndex, true); ui->tableWidget->setColumnHidden(soCostIndex, true); ui->tableWidget->setColumnHidden(soUnitsIndex, true); ui->tableWidget->setColumnHidden(soNotesIndex, true); ui->tableWidget->setColumnHidden(soPaymentIndex, true); ui->tableWidget->setColumnHidden(soCompletePaymentIndex, true); ui->tableWidget->setColumnHidden(soDateIndex, true); ui->tableWidget->setColumnHidden(soIdIndex, true); ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers); ui->tableWidget->setSelectionMode(QAbstractItemView::SingleSelection); m_modelAssigned = true; soModel->setFilter(""); soModel->setSort(8, Qt::DescendingOrder); soModel->select(); ui->tableWidget->resizeRowsToContents(); ui->tableWidget->resizeColumnsToContents(); //changed here because when assigning the date to the datePicker this signal was causing to apply the filter which caused a crash due to that at such time the model was not set up. connect( ui->datePicker, SIGNAL(changed(QDate)), SLOT(applyFilter()) ); } void SOStatus::setDb(QSqlDatabase database) { db = database; if (!db.isOpen()) db.open(); //wait and create model QTimer::singleShot(200, this, SLOT(setupModel())); QTimer::singleShot(300, this, SLOT(populateStatusCombo())); } void SOStatus::populateStatusCombo() { QSqlQuery query(db); Azahar *myDb = new Azahar; myDb->setDatabase(db); ui->statusCombo->addItems(myDb->getStatusListExceptDelivered()); delete myDb; } int SOStatus::getStatusId() { int code=-1; QString currentText = ui->statusCombo->currentText(); Azahar *myDb = new Azahar; myDb->setDatabase(db); code = myDb->getStatusId(currentText); delete myDb; return code; } SOStatus::~SOStatus() { delete ui; } void SOStatus::slotButtonClicked(int button) { if (button == KDialog::Ok) { QDialog::accept(); } else QDialog::reject(); }
9,016
C++
.cpp
210
39.666667
182
0.660207
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
752,816
hash.cpp
hiramvillarreal_iotpos/src/hash.cpp
/*************************************************************************** * Copyright (C) 2013-2015 by Hiram R. Villarreal * * hiramvillarreal.ap@gmail.com * * SHA code from kde kwallet * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "hash.h" #include "sha1.h" #include <assert.h> #include <stdlib.h> #include <QString> #include <QByteArray> #include <QFile> #include <QTextStream> #include <QRegExp> #include <QTime> //#include <iostream> QByteArray Hash::getCheapSalt() { QString result=""; srand( QTime::currentTime().toString("hhmmsszzz").toUInt() ); QRegExp rx("([\\w+]|[\\s*&*%*\\$*#*!*=*¡*\\(*\\)*\\?*\\¿*\\[*\\]*\\{*\\}*\\/*])"); int cont=0; rx.setCaseSensitivity(Qt::CaseInsensitive); while (cont<5) { QString data( rand() ); //if ( rx.indexIn(data) !=-1 ) if (data.contains(rx)) { result+=data; cont++; } } result.resize(5); return result.toLocal8Bit(); } QByteArray Hash::getSalt() { QString result=""; QFile file("/dev/urandom"); //NOTE: At some point of kernel 2.6.32, /dev/random stop working! :( // /dev/urandom is blocking if not enough entropy... so moving mouse or keyboard is needed. But // now with this issue (random failing), urandom seems to work fine and in my tests it has not been blocking. // if (file.open(QIODevice::ReadOnly | QIODevice::Text)) { // // In case /dev/random is a dead fish. // if( !file.waitForReadyRead(100)) file.close(); // } // // if (!file.isOpen()) file.setFileName("/dev/urandom"); // if (file.open(QIODevice::ReadOnly | QIODevice::Text)) { // // In case /dev/random is a dead fish. // if( !file.waitForReadyRead(100)) // file.close(); // } // // if (!file.isOpen()) { // // FIXME: There should be some warning that cheap salt is being used. // qDebug() << "/dev/urandom not responding... Using rand() to get the salt..."; // return getCheapSalt(); // } file.open(QIODevice::ReadOnly | QIODevice::Text); QRegExp rx("[A-Za-z_0-9@#%&\\!\\$\\~\\^\\*]*"); int cont=0; //rx.setCaseSensitivity(Qt::CaseInsensitive); QTextStream in(&file); while (cont<5) { QString data = in.readLine(1); if (!data.isNull() && data.contains(rx) && rx.matchedLength() > 0) { int pos = rx.indexIn(data); if (pos > -1) { result+=data.at(pos); cont++; } } } file.close(); result.resize(5); return result.toLocal8Bit(); } //from Kwalletbackend. // this should be SHA-512 for release probably QString Hash::password2hash(const QByteArray& password) { SHA1 sha; QByteArray hash; hash.resize(20); hash.fill(0); int shasz = sha.size() / 8; assert(shasz >= 20); QByteArray block1(shasz, 0); sha.process(password.data(), qMin(password.size(), 16)); // To make brute force take longer for (int i = 0; i < 2000; i++) { memcpy(block1.data(), sha.hash(), shasz); sha.reset(); sha.process(block1.data(), shasz); } sha.reset(); if (password.size() > 16) { sha.process(password.data() + 16, qMin(password.size() - 16, 16)); QByteArray block2(shasz, 0); // To make brute force take longer for (int i = 0; i < 2000; i++) { memcpy(block2.data(), sha.hash(), shasz); sha.reset(); sha.process(block2.data(), shasz); } sha.reset(); if (password.size() > 32) { sha.process(password.data() + 32, qMin(password.size() - 32, 16)); QByteArray block3(shasz, 0); // To make brute force take longer for (int i = 0; i < 2000; i++) { memcpy(block3.data(), sha.hash(), shasz); sha.reset(); sha.process(block3.data(), shasz); } sha.reset(); if (password.size() > 48) { sha.process(password.data() + 48, password.size() - 48); QByteArray block4(shasz, 0); // To make brute force take longer for (int i = 0; i < 2000; i++) { memcpy(block4.data(), sha.hash(), shasz); sha.reset(); sha.process(block4.data(), shasz); } sha.reset(); // split 14/14/14/14 hash.resize(56); memcpy(hash.data(), block1.data(), 14); memcpy(hash.data() + 14, block2.data(), 14); memcpy(hash.data() + 28, block3.data(), 14); memcpy(hash.data() + 42, block4.data(), 14); block4.fill(0); } else { // split 20/20/16 hash.resize(56); memcpy(hash.data(), block1.data(), 20); memcpy(hash.data() + 20, block2.data(), 20); memcpy(hash.data() + 40, block3.data(), 16); } block3.fill(0); } else { // split 20/20 hash.resize(40); memcpy(hash.data(), block1.data(), 20); memcpy(hash.data() + 20, block2.data(), 20); } block2.fill(0); } else { // entirely block1 hash.resize(20); memcpy(hash.data(), block1.data(), 20); } block1.fill(0); //MCH: to store hash as a String... QString output, tmp; unsigned char *digest; digest = (unsigned char*) hash.data(); for (int i = 0; i < 20; ++i) output += tmp.sprintf("%02x", digest[i]); output = output.toUpper(); return output; }
6,670
C++
.cpp
177
32.559322
118
0.52964
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
752,817
iotpos.cpp
hiramvillarreal_iotpos/src/iotpos.cpp
/************************************************************************** * Copyright © 2013-2015 by Hiram R. Villarreal * * hiramvillarreal.ap@gmail.com * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "iotpos.h" #include "iotposview.h" #include "settings.h" #include "enums.h" #include <kapplication.h> // #include <qpainter.h> #include <kdeversion.h> #include <kglobal.h> #include <kiconloader.h> #include <kmenubar.h> #include <kstatusbar.h> #include <kconfigdialog.h> #include <kfiledialog.h> #include <kactioncollection.h> #include <kaction.h> #include <kstandardaction.h> #include <KLocale> #include <kstandarddirs.h> #include <KNotification> #include <ktoolbar.h> #include <QListWidgetItem> #include <QPushButton> #include <QApplication> #include <QDesktopWidget> #include <QLabel> #include <QTimer> #include <QIcon> #include <QDateTime> #include <QDir> #include <QFileInfoList> #include <QFileInfo> //For a frameless window: KMainWindow(0, Qt::FramelessWindowHint) iotpos::iotpos() : KXmlGuiWindow(), //: KXmlGuiWindow(0,Qt::FramelessWindowHint), m_view(new iotposView()) { setObjectName(QLatin1String("iotpos")); setAcceptDrops(false); // tell the KMainWindow that this is indeed the main widget setCentralWidget(m_view); // then, setup our actions setupActions(); // Add typical actions and save size/toolbars/statusbar statusBar()->show(); //add some info labels to status bar labelUserInfo = new QLabel("::user::"); labelDate = new QLabel(" ::Date:: "); labelTime = new QLabel(" ::Time:: "); labelTransaction = new QLabel(""); QLabel *imageUser = new QLabel("user"); QLabel *imageDate = new QLabel("date"); QLabel *imageTime = new QLabel("time"); QLabel *imageTransaction = new QLabel("trans"); imageUser->setPixmap(DesktopIcon("user-identity", 16)); imageDate->setPixmap(DesktopIcon("view-pim-calendar", 16)); imageTime->setPixmap(DesktopIcon("chronometer", 16)); imageTransaction->setPixmap(DesktopIcon("wallet-open", 16)); updateDate(); statusBar()->addWidget(imageUser); statusBar()->addWidget(labelUserInfo); statusBar()->addWidget(imageDate); statusBar()->addWidget(labelDate); statusBar()->addWidget(imageTime); statusBar()->addWidget(labelTime); statusBar()->addWidget(imageTransaction); statusBar()->addWidget(labelTransaction); connect(m_view, SIGNAL(signalLoggedUser()), SLOT(updateUserName()) ); connect(m_view, SIGNAL(signalNoLoggedUser()), SLOT(updateUserName()) ); connect(m_view, SIGNAL(signalUpdateClock() ), SLOT(updateClock()) ); QTimer::singleShot(500, this, SLOT(hideMenuBar())); // apply the saved mainwindow settings, if any, and ask the mainwindow // to automatically save settings if changed: window size, toolbar // position, icon size, etc. setAutoSaveSettings(); connect(m_view,SIGNAL(signalChangeStatusbar(const QString&)),this,SLOT(changeStatusbar(const QString&))); connect(m_view,SIGNAL(signalChangeCaption(const QString&)),this, SLOT(changeCaption(const QString&))); connect(m_view, SIGNAL(signalAdminLoggedOn()), this, SLOT(enableConfig())); connect(m_view, SIGNAL(signalAdminLoggedOff()), this, SLOT(disableConfig())); connect(m_view, SIGNAL(signalSupervisorLoggedOn()), this, SLOT(enableConfig())); //new connect(m_view, SIGNAL(signalSupervisorLoggedOff()), this, SLOT(disableConfig())); //new connect(m_view, SIGNAL(signalNoLoggedUser()), this, SLOT(disableUi())); connect(m_view, SIGNAL(signalLoggedUser()), this, SLOT(reactOnLogOn())); connect(m_view, SIGNAL(signalStartedOperation()), this, SLOT(reactOnStartedOp()) ); connect(m_view, SIGNAL(signalUpdateTransactionInfo()), this, SLOT(updateTransaction())); connect(m_view, SIGNAL(signalShowProdGrid()), this, SLOT(triggerGridAction())); connect(m_view, SIGNAL(signalShowDbConfig()), this, SLOT(showDBConfigDialog())); connect(m_view, SIGNAL(signalEnableUI()), this, SLOT(enableUi()) ); connect(m_view, SIGNAL(signalDisableUI()), this, SLOT(disableUi()) ); connect(m_view, SIGNAL(signalDisableLogin()), this, SLOT(disableLogin()) ); connect(m_view, SIGNAL(signalEnableLogin()), this, SLOT(enableLogin()) ); connect(m_view, SIGNAL(signalEnableStartOperationAction()), this, SLOT(enableStartOp()) ); connect(m_view, SIGNAL(signalDisableStartOperationAction()), this, SLOT(disableStartOp()) ); loadStyle(); disableConfig(); disableUi(); } void iotpos::triggerGridAction() { QAction *accion = actionCollection()->action("showProductsGrid"); accion->trigger(); qDebug()<<"trigger grid action done..."; } iotpos::~iotpos() { // delete m_printer; } void iotpos::setupActions() { KStandardAction::quit(this, SLOT(salir()), actionCollection()); //KStandardAction::quit(qApp, SLOT(quit()), actionCollection()); KStandardAction::preferences(this, SLOT(optionsPreferences()), actionCollection()); //Our actions QAction* loginAction = actionCollection()->addAction( "login" ); loginAction->setText(i18n("Login")); loginAction->setIcon(KIcon("office-address-book")); //identity loginAction->setShortcut(Qt::CTRL+Qt::Key_L); connect(loginAction, SIGNAL(triggered(bool)),m_view, SLOT(login())); QAction *corteCajaAction = actionCollection()->addAction("balance"); corteCajaAction->setText(i18nc("Account balance", "Balance")); corteCajaAction->setIcon(KIcon("iotpos-balance")); corteCajaAction->setShortcut(Qt::CTRL+Qt::Key_B); connect(corteCajaAction, SIGNAL(triggered(bool)), m_view, SLOT(doCorteDeCaja())); QAction* enterCodeAction = actionCollection()->addAction( "enterCode" ); enterCodeAction->setText(i18n("Enter Code")); enterCodeAction->setIcon(KIcon("iotpos-tag")); enterCodeAction->setShortcut(Qt::Key_F2); connect(enterCodeAction, SIGNAL(triggered(bool)),m_view, SLOT(showEnterCodeWidget())); QAction* searchItemAction = actionCollection()->addAction( "searchItem" ); searchItemAction->setText(i18n("Search Item")); searchItemAction->setIcon(KIcon("edit-find")); searchItemAction->setShortcut(Qt::Key_F3); connect(searchItemAction, SIGNAL(triggered(bool)),m_view, SLOT(showSearchItemWidget())); QAction* delSelectedItemAction = actionCollection()->addAction( "deleteSelectedItem" ); delSelectedItemAction->setText(i18n("Delete Selected Item")); delSelectedItemAction->setIcon(KIcon("iotpos-boxcancel")); delSelectedItemAction->setShortcut(QKeySequence::ZoomOut); //Qt::Key_Delete Qt::Key_Control+Qt::Key_Delete QKeySequence::Cut QKeySequence::ZoomOut connect(delSelectedItemAction, SIGNAL(triggered(bool)),m_view, SLOT(deleteSelectedItem())); // ERROR: I dont know why, in my computer, instead of CTRL-Delete, the key assigned is Shift-( // The same for other non-working shortcuts. // Some problem related to different keyboard layout : qDebug()<<"shortcut:"<<delSelectedItemAction->shortcuts(); QAction* finishTransactionAction = actionCollection()->addAction( "finishTransaction" ); finishTransactionAction->setText(i18n("Finish transaction")); finishTransactionAction->setIcon(KIcon("iotpos-transaction-accept")); finishTransactionAction->setShortcut(Qt::Key_F12); connect(finishTransactionAction, SIGNAL(triggered(bool)),m_view, SLOT(finishCurrentTransaction())); QAction* cancelTransactionAction = actionCollection()->addAction( "cancelTransaction" ); cancelTransactionAction->setText(i18n("Cancel transaction")); cancelTransactionAction->setIcon(KIcon("iotpos-transaction-cancel")); cancelTransactionAction->setShortcut(Qt::Key_F10); connect(cancelTransactionAction, SIGNAL(triggered(bool)),m_view, SLOT(preCancelCurrentTransaction())); QAction* cancelSellAction = actionCollection()->addAction("cancelTicket"); cancelSellAction->setText(i18n("Cancel a ticket")); cancelSellAction->setIcon(KIcon("iotpos-ticket-cancel") ); cancelSellAction->setShortcut(Qt::Key_F11); connect(cancelSellAction, SIGNAL(triggered(bool)),m_view, SLOT(askForIdToCancel())); //NOTE: This action is for setting how much money is on the drawer... QAction* startOperationAction = actionCollection()->addAction( "startOperation" ); startOperationAction->setText(i18n("Start Operation")); startOperationAction->setIcon(KIcon("window-new")); startOperationAction->setShortcut(QKeySequence::New); // New Qt::Key_Control+Qt::Key_N connect(startOperationAction, SIGNAL(triggered(bool)),m_view, SLOT(_slotDoStartOperation())); QAction *payFocusAction = actionCollection()->addAction("payFocus"); payFocusAction->setText(i18n("Pay focus")); payFocusAction->setIcon(KIcon("iotpos-payfocus")); payFocusAction->setShortcut(Qt::Key_F4); //Qt::Key_Alt + Qt::Key_End connect(payFocusAction, SIGNAL(triggered(bool)),m_view, SLOT(focusPayInput())); QAction *showProdGridAction = actionCollection()->addAction("showProductsGrid"); showProdGridAction->setCheckable(true); showProdGridAction->setText(i18n("Show/Hide Products Grid")); showProdGridAction->setIcon(KIcon("view-split-top-bottom")); showProdGridAction->setShortcut(QKeySequence::Print); connect(showProdGridAction, SIGNAL(toggled(bool)), m_view, SLOT(showProductsGrid(bool))); qDebug()<<"Show Grid shortcut:"<<showProdGridAction->shortcuts(); QAction *showPriceCheckerAction = actionCollection()->addAction("showPriceChecker"); showPriceCheckerAction->setText(i18n("Show Price Checker")); showPriceCheckerAction->setIcon(KIcon("iotpos-price-checker")); showPriceCheckerAction->setShortcut(Qt::Key_F9); connect(showPriceCheckerAction, SIGNAL(triggered(bool)), m_view, SLOT(showPriceChecker())); QAction *reprintTicketAction = actionCollection()->addAction("reprintTicket"); reprintTicketAction->setText(i18n("Reprint ticket")); reprintTicketAction->setIcon(KIcon("iotpos-print-ticket")); reprintTicketAction->setShortcut(Qt::Key_F5); connect(reprintTicketAction, SIGNAL(triggered(bool)), m_view, SLOT(showReprintTicket())); QAction *cashOutAction = actionCollection()->addAction("cashOut"); cashOutAction->setText(i18n("Cash Out")); cashOutAction->setIcon(KIcon("iotpos-cashout")); cashOutAction->setShortcut(Qt::Key_F7); //F7 connect(cashOutAction, SIGNAL(triggered(bool)), m_view, SLOT(cashOut())); QAction *cashAvailableAction = actionCollection()->addAction("cashAvailable"); cashAvailableAction->setText(i18n("Cash in drawer")); cashAvailableAction->setIcon(KIcon("iotpos-money")); cashAvailableAction->setShortcut(Qt::Key_F6); connect(cashAvailableAction, SIGNAL(triggered(bool)), m_view, SLOT(cashAvailable())); QAction *cashInAction = actionCollection()->addAction("cashIn"); cashInAction->setText(i18n("Cash In")); cashInAction->setIcon(KIcon("iotpos-cashin")); cashInAction->setShortcut(Qt::Key_F8); //F8 connect(cashInAction, SIGNAL(triggered(bool)), m_view, SLOT(cashIn())); QAction *endOfDayAction = actionCollection()->addAction("endOfDay"); endOfDayAction->setText(i18n("End of day report")); endOfDayAction->setIcon(KIcon("go-jump-today")); endOfDayAction->setShortcut(QKeySequence::Close); connect(endOfDayAction, SIGNAL(triggered(bool)), m_view, SLOT(endOfDay())); qDebug()<<"End of day shortcut:"<<endOfDayAction->shortcuts(); QAction *soAction = actionCollection()->addAction("specialOrder"); soAction->setText(i18n("Add Special Order")); soAction->setIcon(KIcon("iotpos-box")); soAction->setShortcut(Qt::Key_PageUp); connect(soAction, SIGNAL(triggered(bool)), m_view, SLOT(addSpecialOrder())); qDebug()<<"SpecialOrder shortcut:"<<soAction->shortcuts(); QAction *socAction = actionCollection()->addAction("specialOrderComplete"); socAction->setText(i18n("Complete Special Order")); socAction->setIcon(KIcon("iotpos-box")); socAction->setShortcut(Qt::Key_PageDown); connect(socAction, SIGNAL(triggered(bool)), m_view, SLOT(specialOrderComplete())); qDebug()<<"SpecialOrder Complete shortcut:"<<socAction->shortcuts(); QAction *lockAction = actionCollection()->addAction("lockScreen"); lockAction->setText(i18n("Lock Screen")); lockAction->setIcon(KIcon("iotpos-box")); //TODO:CREATE ICON! lockAction->setShortcut(Qt::CTRL+Qt::Key_Space); connect(lockAction, SIGNAL(triggered(bool)), m_view, SLOT(lockScreen())); qDebug()<<"LockScreen shortcut:"<<lockAction->shortcuts(); QAction *suspendSaleAction = actionCollection()->addAction("suspendSale"); suspendSaleAction->setText(i18n("Suspend Sale")); suspendSaleAction->setIcon(KIcon("iotpos-suspend")); suspendSaleAction->setShortcut(Qt::CTRL+Qt::Key_Backspace); connect(suspendSaleAction, SIGNAL(triggered(bool)), m_view, SLOT( suspendSale() )); qDebug()<<"Suspend Sale shortcut:"<<suspendSaleAction->shortcuts(); QAction *soStatusAction = actionCollection()->addAction("soStatus"); soStatusAction->setText(i18n("Change Special Order Status")); soStatusAction->setIcon(KIcon("iotpos-box")); //TODO:CREATE ICON! soStatusAction->setShortcut(Qt::CTRL+Qt::Key_PageUp); connect(soStatusAction, SIGNAL(triggered(bool)), m_view, SLOT( changeSOStatus() )); qDebug()<<"soStatus shortcut:"<<soStatusAction->shortcuts(); QAction *oDiscAction = actionCollection()->addAction("occasionalDiscount"); oDiscAction->setText(i18n("Change Special Order Status")); oDiscAction->setIcon(KIcon("iotpos-money")); //TODO:CREATE ICON! oDiscAction->setShortcut(Qt::CTRL+Qt::Key_D); connect(oDiscAction, SIGNAL(triggered(bool)), m_view, SLOT( occasionalDiscount() )); qDebug()<<"occasionalDiscount shortcut:"<<oDiscAction->shortcuts(); QAction *resumeAction = actionCollection()->addAction("resumeSale"); resumeAction->setText(i18n("Resume Sale")); resumeAction->setIcon(KIcon("iotpos-resume")); resumeAction->setShortcut(Qt::CTRL+Qt::Key_R); connect(resumeAction, SIGNAL(triggered(bool)), m_view, SLOT( resumeSale() )); qDebug()<<"resumeSale shortcut:"<<resumeAction->shortcuts(); QAction *makeReservationA = actionCollection()->addAction("makeReservation"); makeReservationA->setText(i18n("Reserve Items")); makeReservationA->setIcon(KIcon("iotpos-reservation")); makeReservationA->setShortcut(Qt::ALT + Qt::Key_R); // Qt::ALT is the left ALT key ( not the Alt Gr ) connect(makeReservationA, SIGNAL(triggered(bool)), m_view, SLOT( reserveItems() )); qDebug()<<"makeReservation shortcut:"<<makeReservationA->shortcuts(); QAction *resumeRAction = actionCollection()->addAction("resumeReservation"); resumeRAction->setText(i18n("Reservations")); resumeRAction->setIcon(KIcon("iotpos-reservation-view")); resumeRAction->setShortcut(Qt::CTRL+Qt::SHIFT+Qt::Key_R); connect(resumeRAction, SIGNAL(triggered(bool)), m_view, SLOT( resumeReservation() )); qDebug()<<"Reservations shortcut:"<<resumeRAction->shortcuts(); QAction *showCreditsAction = actionCollection()->addAction("showCredits"); showCreditsAction->setText(i18n("Show Credits")); showCreditsAction->setIcon(KIcon("iotpos-credits")); showCreditsAction->setShortcut(Qt::CTRL+Qt::SHIFT+Qt::Key_C); connect(showCreditsAction, SIGNAL(triggered(bool)), m_view, SLOT( showCredits() )); qDebug()<<"ShowCredits shortcut:"<<showCreditsAction->shortcuts(); QAction *addResPaymentAction = actionCollection()->addAction("addReservationPayment"); addResPaymentAction->setText(i18n("Add Reservation Payment")); addResPaymentAction->setIcon(KIcon("iotpos-reservation-payment")); addResPaymentAction->setShortcut(Qt::CTRL+Qt::SHIFT+Qt::Key_P); connect(addResPaymentAction, SIGNAL(triggered(bool)), m_view, SLOT( addReservationPayment() )); qDebug()<<"ReservationPayment shortcut:"<<addResPaymentAction->shortcuts(); //NOTE: There is a weird bug: When the iotpos-reservation-* icon is used at 22x22 pixels (default/medium size) it is not found, instead used iotpos app icon. setupGUI(); //FIXME: SCREEN SIZE int y = (QApplication::desktop()->height()); if (y < 640){ setWindowState( windowState() | Qt::WindowFullScreen); // set } else { setWindowState( windowState() | Qt::WindowMaximized); }// set //setGeometry(QApplication::desktop()->screenGeometry(this)); if (!Settings::splitterSizes().isEmpty()) m_view->setTheSplitterSizes(Settings::splitterSizes()); if (!Settings::gridSplitterSizes().isEmpty()) m_view->setTheGridSplitterSizes(Settings::gridSplitterSizes()); } void iotpos::loadStyle() { // QString defaultStyle = QApplication::style()->metaObject()->className(); // qDebug()<<"Default Style:"<<defaultStyle; // qDebug()<<"QStyles Available:"<<QStyleFactory::keys(); // //qApp->setStyle("Plastik"); // defaultStyle = QApplication::style()->metaObject()->className(); // qDebug()<<"Style used:"<<defaultStyle; qDebug()<<"Loading Stylesheet..."; if (Settings::useStyle()) { QString fileName; QString path; path = KStandardDirs::locate("appdata", "styles/"); fileName = path + Settings::styleName() + "/" + Settings::styleName() + ".qss"; QFile file(fileName); bool op = file.open(QFile::ReadOnly); QString styleSheet = QLatin1String(file.readAll()); //replace fakepath to the real path.. QString finalStyle = styleSheet.replace("[STYLE_PATH]", path + Settings::styleName() + "/"); qApp->setStyleSheet(finalStyle); if (op) file.close(); } else { //Load a simple style... QString fileName; QString path; path = KStandardDirs::locate("appdata", "styles/"); fileName = path + Settings::styleName() + "/simple.qss"; QFile file(fileName); bool op = file.open(QFile::ReadOnly); QString styleSheet = QLatin1String(file.readAll()); //replace fakepath to the real path.. QString finalStyle = styleSheet.replace("[STYLE_PATH]", path + Settings::styleName() + "/"); qApp->setStyleSheet(finalStyle); if (op) file.close(); } showToolBars(); } /**This is used to get Database user,password,server to set initial config, in case the db server is remote. So we show the config dialog, and when saved login again. It is called from main_view.login() **/ void iotpos::showDBConfigDialog() { //avoid to have 2 dialogs shown if ( KConfigDialog::showDialog( "settings" ) ) { return; } KConfigDialog *dialog = new KConfigDialog(this, "settings", Settings::self()); QWidget *dbSettingsDlg = new QWidget; ui_prefs_db.setupUi(dbSettingsDlg); dialog->addPage(dbSettingsDlg, i18n("Database"), "kexi"); // book connect(dialog, SIGNAL(settingsChanged(QString)), m_view, SLOT(settingsChangedOnInitConfig())); dialog->setAttribute( Qt::WA_DeleteOnClose ); dialog->show(); qDebug()<<"CONFIG DIALOG SHOWN... - showDBConfigDialog()"; } void iotpos::optionsPreferences() { //avoid to have 2 dialogs shown if ( KConfigDialog::showDialog( "settings" ) ) { return; } KConfigDialog *dialog = new KConfigDialog(this, "settings", Settings::self()); QWidget *generalSettingsDlg = new QWidget; ui_prefs_base.setupUi(generalSettingsDlg); dialog->addPage(generalSettingsDlg, i18n("General"), "configure"); QWidget *storeDataSettingsDlg = new QWidget; ui_store_data.setupUi(storeDataSettingsDlg); //NOTE: What icon to use for this?? dialog->addPage(storeDataSettingsDlg, i18n("Store"), "go-home"); QWidget *dbSettingsDlg = new QWidget; ui_prefs_db.setupUi(dbSettingsDlg); dialog->addPage(dbSettingsDlg, i18n("Database"), "kexi"); // book QWidget *styleSettingsDlg = new QWidget; ui_pref_style.setupUi(styleSettingsDlg); dialog->addPage(styleSettingsDlg, i18n("Appearence"), "draw-brush"); iotpos::populateStyleList(); connect(ui_pref_style.styleList, SIGNAL(itemClicked(QListWidgetItem *)), SLOT(sLitemActivated(QListWidgetItem *)) ); connect(ui_pref_style.styleList, SIGNAL(itemActivated(QListWidgetItem *)), SLOT(sLitemActivated(QListWidgetItem *)) ); QWidget *securitySettingsDlg = new QWidget; ui_pref_security.setupUi(securitySettingsDlg); dialog->addPage(securitySettingsDlg, i18n("Security"), "dialog-password"); QWidget *printersSettingDlg = new QWidget; ui_pref_printers.setupUi(printersSettingDlg); dialog->addPage(printersSettingDlg, i18n("Printer"), "iotpos-printer"); connect(dialog, SIGNAL(settingsChanged(QString)), m_view, SLOT(settingsChanged())); connect(dialog, SIGNAL(settingsChanged(const QString &)), this, SLOT(loadStyle())); //free mem by deleting the dialog on close without waiting for deletingit when the application quits dialog->setAttribute( Qt::WA_DeleteOnClose ); dialog->show(); } void iotpos::hideToolBars() { QList<KToolBar*> tb = toolBars(); for (int i=0; i < tb.count(); i++) tb.at(i)->hide(); } void iotpos::showToolBars() { QList<KToolBar*> tb = toolBars(); for (int i=0; i < tb.count(); i++) tb.at(i)->show(); } void iotpos::hideMenuBar() { if (!menuBar()->isHidden()) { menuBar()->hide(); } } void iotpos::reactOnStartedOp() { if (m_view->canStartSelling()) { enableUi(); //disableStartOp(); } else { disableUi(); //enableStartOp(); } } void iotpos::enableStartOp() { qDebug()<<"enabling start op action, logged user:"<<m_view->getLoggedUser(); if (!m_view->canStartSelling() && !m_view->getLoggedUser().isEmpty()) { QAction *action = actionCollection()->action("startOperation"); action->setEnabled(true); } } void iotpos::disableStartOp() { qDebug()<<"disabling start op action, logged user:"<<m_view->getLoggedUser(); QAction *action = actionCollection()->action("startOperation"); action->setDisabled(true); } void iotpos::reactOnLogOn() { if (m_view->canStartSelling()) enableUi(); else { disableUi(); QString msg = i18n("Administrator or Supervisor needs to start operation before you can start selling..."); //Show a dialog saying that operations need to be started by admin ??? if (m_view->getLoggedUserRole() == roleBasic ) { KNotification *notify = new KNotification("information", this); notify->setText(msg); QPixmap pixmap = DesktopIcon("dialog-information",48); notify->setPixmap(pixmap); notify->sendEvent(); } } } void iotpos::disableUi() { m_view->frame->setDisabled(true); m_view->frameLeft->setDisabled(true); QAction *action = actionCollection()->action("enterCode"); action->setDisabled(true); if (m_view->canStartSelling()) { action = actionCollection()->action("startOperation"); action->setDisabled(true); } action = actionCollection()->action("searchItem"); action->setDisabled(true); action = actionCollection()->action("deleteSelectedItem"); action->setDisabled(true); action = actionCollection()->action("finishTransaction"); action->setDisabled(true); action = actionCollection()->action("cancelTransaction"); action->setDisabled(true); action = actionCollection()->action("balance"); action->setDisabled(true); action = actionCollection()->action("payFocus"); action->setDisabled(true); action = actionCollection()->action("cancelTicket"); action->setDisabled(true); action = actionCollection()->action("showProductsGrid"); action->setDisabled(true); action = actionCollection()->action("cashIn"); action->setDisabled(true); action = actionCollection()->action("cashOut"); action->setDisabled(true); action = actionCollection()->action("cashAvailable"); action->setDisabled(true); action = actionCollection()->action("reprintTicket"); action->setDisabled(true); action = actionCollection()->action("showPriceChecker"); action->setDisabled(true); action = actionCollection()->action("endOfDay"); action->setDisabled(true); action = actionCollection()->action("specialOrder"); action->setDisabled(true); action = actionCollection()->action("specialOrderComplete"); action->setDisabled(true); action = actionCollection()->action("occasionalDiscount"); action->setDisabled(true); action = actionCollection()->action("suspendSale"); action->setDisabled(true); action = actionCollection()->action("resumeSale"); action->setDisabled(true); action = actionCollection()->action("makeReservation"); action->setDisabled(true); action = actionCollection()->action("resumeReservation"); action->setDisabled(true); action = actionCollection()->action("showCredits"); action->setDisabled(true); action = actionCollection()->action("addReservationPayment"); action->setDisabled(true); action = actionCollection()->action("login"); action->setEnabled(true); //enable login! disableConfig(); } void iotpos::disableLogin() { QAction *action = actionCollection()->action("login"); action->setDisabled(true); } void iotpos::enableLogin() { QAction *action = actionCollection()->action("login"); action->setEnabled(true); } void iotpos::enableUi() { m_view->setEnabled(true); m_view->frame->setEnabled(true); m_view->frameLeft->setEnabled(true); QAction *action = actionCollection()->action("enterCode"); action->setEnabled(true); action = actionCollection()->action("startOperation"); action->setDisabled(true); action = actionCollection()->action("searchItem"); action->setEnabled(true); action = actionCollection()->action("deleteSelectedItem"); action->setEnabled(true); action = actionCollection()->action("finishTransaction"); action->setEnabled(true); action = actionCollection()->action("cancelTransaction"); action->setEnabled(true); action = actionCollection()->action("balance"); action->setEnabled(true); action = actionCollection()->action("payFocus"); action->setEnabled(true); action = actionCollection()->action("cancelTicket"); action->setEnabled(true); action = actionCollection()->action("showProductsGrid"); action->setEnabled(true); action = actionCollection()->action("cashIn"); action->setEnabled(true); action = actionCollection()->action("cashOut"); action->setEnabled(true); action = actionCollection()->action("cashAvailable"); action->setEnabled(true); action = actionCollection()->action("reprintTicket"); action->setEnabled(true); action = actionCollection()->action("showPriceChecker"); action->setEnabled(true); action = actionCollection()->action("endOfDay"); action->setEnabled(true); action = actionCollection()->action("specialOrder"); action->setEnabled(true); action = actionCollection()->action("specialOrderComplete"); action->setEnabled(true); action = actionCollection()->action("occasionalDiscount"); action->setEnabled(true); action = actionCollection()->action("suspendSale"); action->setEnabled(true); action = actionCollection()->action("resumeSale"); action->setEnabled(true); action = actionCollection()->action("resumeReservation"); action->setEnabled(true); action = actionCollection()->action("makeReservation"); action->setEnabled(true); action = actionCollection()->action("addReservationPayment"); action->setEnabled(true); action = actionCollection()->action("showCredits"); action->setEnabled(true); if (m_view->canStartSelling()) { // action = actionCollection()->action("suspendSale"); // action->setEnabled(true); } } void iotpos::disableConfig() { QAction *actPref = actionCollection()->action(KStandardAction::stdName(KStandardAction::Preferences)); actPref->setDisabled(true); QAction *actQuit = actionCollection()->action(KStandardAction::stdName(KStandardAction::Quit)); //FIXME: esto no es muy bueno en produccion.. if (!Settings::allowAnyUserToQuit()) actQuit->setDisabled(true); } void iotpos::enableConfig() { QAction *actPref = actionCollection()->action(KStandardAction::stdName(KStandardAction::Preferences)); actPref->setEnabled(true); QAction *actQuit = actionCollection()->action(KStandardAction::stdName(KStandardAction::Quit)); actQuit->setEnabled(true); QAction *actSop = actionCollection()->action("startOperation"); actSop->setEnabled(true); } void iotpos::populateStyleList() { QString path = KStandardDirs::locate("appdata", "styles/"); QDir dir(path); dir.setFilter(QDir::Dirs | QDir::NoSymLinks | QDir::NoDotAndDotDot); dir.setSorting(QDir::Name | QDir::LocaleAware); QFileInfoList list = dir.entryInfoList(); for (int i = 0; i < list.size(); ++i) { QFileInfo fileInfo = list.at(i); ui_pref_style.styleList->addItem(fileInfo.fileName()); } //Select the style used... QList<QListWidgetItem *> itemLfound = ui_pref_style.styleList->findItems(Settings::styleName(), Qt::MatchExactly); if (itemLfound.count() == 1) { QListWidgetItem *item = itemLfound.first(); ui_pref_style.styleList->setCurrentItem(item); } } void iotpos::sLitemActivated(QListWidgetItem * item) { ui_pref_style.kcfg_styleName->setText(item->text()); } void iotpos::updateClock() { QTime time = QTime::currentTime(); QString text = time.toString("hh:mm"); if ((time.second() % 2) == 0) text[2] = '.'; labelTime->setText(text); if ((time.hour()==0) && (time.minute()==0) && (time.second()==0) ) updateDate(); ///On kde 4.3 some bug resizes the window and the taskbar over mainview. I dont want taskbar, it means full screen is deactivated. How can we set fullScreen MODE? if (geometry() != QApplication::desktop()->screenGeometry(this)) { //qDebug()<<"FIXING WINDOW SIZE from:"<<geometry(); //setGeometry(QApplication::desktop()->screenGeometry(this)); //Doing this the size is fixed but the taskbar is show over mainview } } void iotpos::updateDate() { QDate dt = QDate::currentDate(); labelDate->setText(KGlobal::locale()->formatDate(dt)); } void iotpos::updateUserName() { if (m_view->getLoggedUserRole() == roleBasic) labelUserInfo->setText(m_view->getLoggedUser()); else if (m_view->getLoggedUserRole() == roleSupervisor) labelUserInfo->setText(QString("<html><font color=orange><b>%1</font></b>").arg(m_view->getLoggedUser())); else labelUserInfo->setText(QString("<html><font color=red><b>%1</font></b>").arg(m_view->getLoggedUser())); } void iotpos::updateTransaction() { QString tn = m_view->getCurrentTransactionString(); labelTransaction->setText(i18n(" #%1", tn)); } void iotpos::changeStatusbar(const QString& text) { // display the text on the statusbar statusBar()->showMessage(text, 1500); } void iotpos::changeCaption(const QString& text) { // display the text on the caption setCaption(text); } bool iotpos::queryClose() { int ss1 = m_view->getTheSplitterSizes().at(0); //The main splitter height int ss2 = m_view->getTheGridSplitterSizes().at(0); //The gridView spliiter height qDebug()<<" LeftPanel splitter size:"<<ss1; qDebug()<<" GridView splitter size:"<<ss2; //Check if the gridview is hidden, to do not save its 0 size values. if ( ss1 >= 50) Settings::setSplitterSizes(m_view->getTheSplitterSizes()); if ( ss2 >= 50) Settings::setGridSplitterSizes(m_view->getTheGridSplitterSizes()); //FIXED Settings::writeConfig(); Settings::self()->writeConfig(); //Close only by admin user. or ask for password?? if (Settings::allowAnyUserToQuit()) { bool reallyQuit=false; if (m_view->getLoggedUser() == "admin") reallyQuit=true; else reallyQuit = m_view->validAdminUser(); //cancel current transaction if (m_view->isTransactionInProgress()){ m_view->cancelByExit(); } //save balance //m_view->saveBalance(); //When saving balance on quit, do we need to print the balance??? m_view->corteDeCaja(); return reallyQuit; } else if ( m_view->getLoggedUser() == "admin" ) { //cancel current transaction if (m_view->isTransactionInProgress()){ m_view->cancelByExit(); } //save balance //m_view->saveBalance(); //When saving balance on quit, do we need to print the balance??? m_view->corteDeCaja(); return true; } else return false; } void iotpos::salir() { if (queryClose()) { qDebug()<<"===EXIT IOTPOS AT "<<QDateTime::currentDateTime().toString(); kapp->quit(); } } #include "iotpos.moc"
33,258
C++
.cpp
708
43.69209
164
0.719013
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
752,818
Currency.cpp
hiramvillarreal_iotpos/src/nouns/Currency.cpp
#include "Currency.h" #include <QTextStream> Currency::Currency() { this->amount = 0; } Currency::Currency(double amount) { this->amount = amount * 100.0 + 0.5; } Currency::~Currency() { } void Currency::set(Currency newValue) { this->amount = newValue.amount; } void Currency::set(double newValue) { this->amount = newValue * 100.0 + 0.5; } void Currency::substract(Currency currency) { this->amount -= currency.amount; } void Currency::add(Currency currency) { this->amount += currency.amount; } void Currency::multiply(double multiplier) { this->amount = this->amount * multiplier + 0.5; } void Currency::divide(double divider) { this->amount = this->amount / divider + 0.5; } double Currency::toDouble() const { double result = this->amount / 100.0; return result; } QString Currency::toString() const { QString result; QTextStream out(&result); out.setRealNumberPrecision(2); out.setRealNumberNotation(QTextStream::FixedNotation); out << this->toDouble(); return result; } QTextStream& operator<<(QTextStream& os, const Currency& obj) { os << obj.toString(); return os; } QDebug& operator<<(QDebug& os, const Currency& obj) { os << obj.toString(); return os; }
1,261
C++
.cpp
57
19.45614
63
0.70143
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
752,819
BasketPriceSummary.cpp
hiramvillarreal_iotpos/src/nouns/BasketPriceSummary.cpp
// // Created by krzysiek on 15.04.15. // #include "BasketPriceSummary.h" #include <QDebug> BasketPriceSummary::BasketPriceSummary() { } BasketPriceSummary::BasketPriceSummary(Currency net, Currency gross, Currency tax, Currency discountGross, qulonglong points) { this->net = net; this->gross = gross; this->tax = tax; this->discountGross = discountGross; this->points = points; } QString BasketPriceSummary::toString() { QString result; QTextStream out(&result); out.setRealNumberPrecision(2); out.setRealNumberNotation(QTextStream::FixedNotation); out.setFieldWidth(10); out.setFieldAlignment(QTextStream::AlignLeft); out << "net" << net << "gross" << gross << "tax" << tax << "discount" << discountGross << "points" << points; return result; } void BasketPriceSummary::add(BasketEntryPriceSummary basketEntryPriceSummary) { QString before = this->toString(); net.add(basketEntryPriceSummary.getNet()); gross.add(basketEntryPriceSummary.getGross()); tax.add(basketEntryPriceSummary.getTax()); discountGross.add(basketEntryPriceSummary.getDiscountGross()); points += basketEntryPriceSummary.getPoints(); qDebug() << "!!! Adding: " << basketEntryPriceSummary.toString() << "\nto: " << before << "\nthat gives: " << this->toString(); } BasketPriceSummary::~BasketPriceSummary() { } Currency BasketPriceSummary::getNet() { return this->net; } Currency BasketPriceSummary::getGross() { return this->gross; } Currency BasketPriceSummary::getTax() { return this->tax; } Currency BasketPriceSummary::getDiscountGross() { return this->discountGross; } qulonglong BasketPriceSummary::getPoints() { return this->points; }
1,739
C++
.cpp
50
31.5
142
0.728955
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
752,820
User.cpp
hiramvillarreal_iotpos/src/nouns/User.cpp
#include "User.h" User::User() { } User::~User() { } Salesman::Salesman() { } Salesman::~Salesman() { } Customer::Customer() { } Customer::~Customer() { }
167
C++
.cpp
13
10.923077
23
0.647887
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
752,821
BasketEntryPriceSummary.cpp
hiramvillarreal_iotpos/src/nouns/BasketEntryPriceSummary.cpp
#include "BasketEntryPriceSummary.h" #include <QTextStream> BasketEntryPriceSummary::BasketEntryPriceSummary(double net, double gross, double tax, double discountGross, qulonglong points) { this->net = Currency(net); this->gross = Currency(gross); this->tax = Currency(tax); this->discountGross = Currency(discountGross); this->points = points; } BasketEntryPriceSummary::BasketEntryPriceSummary(Currency net, Currency gross, Currency tax, Currency discountGross, qulonglong points) { this->net = net; this->gross = gross; this->tax = tax; this->discountGross = discountGross; this->points = points; } BasketEntryPriceSummary::~BasketEntryPriceSummary() { } QString BasketEntryPriceSummary::toString() { QString result; QTextStream out(&result); out.setRealNumberPrecision(2); out.setRealNumberNotation(QTextStream::FixedNotation); out.setFieldWidth(10); out.setFieldAlignment(QTextStream::AlignLeft); QString points = QString::number(this->points); out << "net" << net << "gross" << gross << "tax" << tax << "discount" << discountGross << "points" << points; return result; } Currency BasketEntryPriceSummary::getNet() { return this->net; } Currency BasketEntryPriceSummary::getGross() { return this->gross; } Currency BasketEntryPriceSummary::getTax() { return this->tax; } Currency BasketEntryPriceSummary::getDiscountGross() { return this->discountGross; } qulonglong BasketEntryPriceSummary::getPoints() { return this->points; }
1,540
C++
.cpp
44
31.590909
137
0.74428
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
752,822
subcategoryeditor.cpp
hiramvillarreal_iotpos/iotstock/src/subcategoryeditor.cpp
/*************************************************************************** * Copyright © 2012 by Miguel Chavez Gamboa * * hiramvillarreal.ap@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include <KLocale> #include <KMessageBox> #include <KFileDialog> #include <QByteArray> #include "subcategoryeditor.h" #include "../../dataAccess/azahar.h" SubcategoryEditorUI::SubcategoryEditorUI( QWidget *parent ) : QFrame( parent ) { setupUi( this ); } SubcategoryEditor::SubcategoryEditor( QWidget *parent ) : KDialog( parent ) { ui = new SubcategoryEditorUI( this ); setMainWidget( ui ); //setCaption( i18n("Subcategory Editor") ); setButtons( KDialog::Ok|KDialog::Cancel ); enableButtonOk(false); connect(ui->editName, SIGNAL(textEdited(const QString &)), SLOT(checkValid()) ); connect(ui->btnAdd, SIGNAL(clicked()), SLOT(addNewChild())); QTimer::singleShot(1000, this, SLOT(checkValid())); } SubcategoryEditor::~SubcategoryEditor() { delete ui; } void SubcategoryEditor::setDb(QSqlDatabase d) { db = d; if (!db.isOpen()) {db.open();} } //this needs to be called after creating the dialog. void SubcategoryEditor::populateList(QStringList list, QStringList checkedList) { ui->listView->clear(); ui->listView->addItems( list ); for(int i=0;i<ui->listView->count();i++) { ui->listView->item(i)->setFlags(ui->listView->item(i)->flags() |Qt::ItemIsUserCheckable); if ( checkedList.contains(ui->listView->item(i)->text() ) ) ui->listView->item(i)->setCheckState(Qt::Checked); else ui->listView->item(i)->setCheckState(Qt::Unchecked); } } QStringList SubcategoryEditor::getChildren() { //returns a list of checked children. QStringList result; for(int i=0;i<ui->listView->count();i++){ if (ui->listView->item(i)->checkState()) result.append( ui->listView->item(i)->text() ); } return result; } void SubcategoryEditor::checkValid() { bool validText = !ui->editName->text().isEmpty(); enableButtonOk(validText); } void SubcategoryEditor::setDialogType(int t) { //Types: 0:unset, 1:AddDepartment, 2:AddCategory, 3:AddSubcategory. dialogType = t; if (t == 1) setCaption( i18n("Department Editor") ); else if (t == 2) setCaption( i18n("Category Editor") ); else if (t == 3) setCaption( i18n("Subcategory Editor") ); else setCaption( i18n("") ); } void SubcategoryEditor::addNewChild() { //launch dialog to ask for the new child. Using this same dialog. SubcategoryEditor *scEditor = new SubcategoryEditor(this); scEditor->setDb(db); Azahar *myDb = new Azahar; myDb->setDatabase(db); scEditor->setCatList( catList ); scEditor->setScatList( scatList ); scEditor->setDialogType(dialogType+1);//incrementing because this dialog is a child dialog (parentType+1) if (dialogType == 1) { //From "Add Department" dialog, creating a category. scEditor->setLabelForName(i18n("New category:")); scEditor->setLabelForList(i18n("Select the child subcategories for this category:")); scEditor->populateList( myDb->getSubCategoriesList() ); } else if (dialogType == 2) { //From "Add Category" dialog, creating a subcategory. No child allowed. scEditor->setLabelForName(i18n("New subcategory:")); scEditor->setLabelForList(i18n("")); scEditor->hideListView(); //subcategories does not have children. } if ( scEditor->exec() ) { QString text = scEditor->getName(); QStringList children = scEditor->getChildren(); qDebug()<<text<<" CHILDREN:"<<children; if (dialogType == 1) { //The dialog is launched from the "Add Department" dialog. So we are going to create a category. //Create the category if (!myDb->insertCategory(text)) { qDebug()<<"Error:"<<myDb->lastError(); delete myDb; return; } //insert new category to the box catList << text; ui->listView->addItem(text); //mark item as checkable ui->listView->item(ui->listView->count()-1)->setFlags(ui->listView->item(ui->listView->count()-1)->flags() |Qt::ItemIsUserCheckable); ui->listView->item(ui->listView->count()-1)->setCheckState(Qt::Checked); //mark as checked. qulonglong cId = myDb->getCategoryId(text); //create the m2m relations for the new category->subcategory. foreach(QString cat, children) { //get subcategory id qulonglong scId = myDb->getSubCategoryId(cat); //create the link [category] --> [subcategory] myDb->insertM2MCategorySubcategory(cId, scId); } } else if (dialogType == 2) { //The dialog is launched from the "Add Category" dialog. So we are going to create a subcategory which does have a child. //Create the subcategory only... no m2m relation if (!myDb->insertSubCategory(text)) { qDebug()<<"Error:"<<myDb->lastError(); delete myDb; return; } //insert new subcategory to the box scatList << text; ui->listView->addItem(text); //mark item as checkable ui->listView->item(ui->listView->count()-1)->setFlags(ui->listView->item(ui->listView->count()-1)->flags() |Qt::ItemIsUserCheckable); ui->listView->item(ui->listView->count()-1)->setCheckState(Qt::Checked); //mark as checked. }// dialogType == 2 } } #include "subcategoryeditor.moc"
6,966
C++
.cpp
154
38.876623
159
0.592391
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
752,823
clienteditor.cpp
hiramvillarreal_iotpos/iotstock/src/clienteditor.cpp
/*************************************************************************** * Copyright (C) 2013-2015 by Hiram R. Villarreal * * hiramvillarreal.ap@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include <KLocale> #include <KMessageBox> #include <KFileDialog> #include <QByteArray> #include "clienteditor.h" #include "../../mibitWidgets/mibitlineedit.h" ClientEditorUI::ClientEditorUI( QWidget *parent ) : QFrame( parent ) { setupUi( this ); } ClientEditor::ClientEditor( QWidget *parent ) : KDialog( parent ) { ui = new ClientEditorUI( this ); setMainWidget( ui ); setCaption( i18n("Customer Editor") ); setButtons( KDialog::Ok|KDialog::Cancel ); setDefaultButton(KDialog::NoDefault); //disable default button (return Pressed) enableButton(KDialog::Ok, false); connect( ui->btnChangeClientPhoto , SIGNAL( clicked() ), this, SLOT( changePhoto() ) ); connect( ui->editClientName, SIGNAL(textEdited(const QString &)),this, SLOT( checkNameDelayed()) ); connect(ui->editClientCode, SIGNAL(returnPressed()),ui->editClientName, SLOT(setFocus()) ); connect(ui->editClientCode, SIGNAL(editingFinished()),this, SLOT( checkNameDelayed() )); //both returnPressed and lost focus fires this signal. But only fired if validator is accepted. QRegExp regexpC("[0-9]{1,13}"); QRegExpValidator * validator = new QRegExpValidator(regexpC, this); ui->editClientPoints->setValidator(validator); ui->editClientDiscount->setValidator((new QDoubleValidator(0.00, 100.000, 3,ui->editClientDiscount))); //code can contain letters (for ids with letters, like RFC in Mexico) QRegExp regexpName("[A-Za-z_0-9\\s\\\\/\\-]+");//any letter, number, both slashes, dash and lower dash. and any space QRegExpValidator *regexpAlpha = new QRegExpValidator(regexpName, this); ui->editClientCode->setValidator(regexpAlpha); //Set filter to the name. Do not allow .,&^% etc... ui->editClientName->setValidator(regexpAlpha); ui->editClientCode->setEmptyMessage(i18n("Enter a 6, 12, or 13 digits Bar Code.")); ui->editClientName->setEmptyMessage(i18n("Enter customer full name")); ui->editClientPhone->setEmptyMessage(i18n("Phone number")); ui->editClientCell->setEmptyMessage(i18n("E-mail")); ui->editClientPoints->setEmptyMessage(i18n("Accumulated points")); ui->editClientDiscount->setEmptyMessage(i18n("Personal discount")); //since date picker ui->sinceDatePicker->setDate(QDate::currentDate()); QTimer::singleShot(750, this, SLOT(checkName())); ui->editClientCode->setFocus(); } ClientEditor::~ClientEditor() { delete ui; } void ClientEditor::changePhoto() { QString fname = KFileDialog::getOpenFileName(); if (!fname.isEmpty()) { QPixmap p = QPixmap(fname); setPhoto(p); } } void ClientEditor::checkNameDelayed() { QTimer::singleShot(750, this, SLOT(checkName())); } void ClientEditor::checkName() { if (ui->editClientCode->hasFocus()) { enableButtonOk(false); } else { if (ui->editClientName->text().isEmpty()) enableButtonOk(false); else enableButtonOk(true); } } #include "clienteditor.moc"
4,436
C++
.cpp
93
44.258065
188
0.618464
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
752,824
iotstockview.cpp
hiramvillarreal_iotpos/iotstock/src/iotstockview.cpp
/************************************************************************** * Copyright © 2007-2012 by Miguel Chavez Gamboa * * hiramvillarreal.ap@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #define QT_GUI_LIB //The above line is because that define is needed, and as i dont use qmake, i must define it here.. //And only caused problems with the QSqlRelationalDelegate.. what a thing. #include "iotstockview.h" #include "settings.h" #include "usersdelegate.h" #include "usereditor.h" #include "clienteditor.h" #include "promoeditor.h" #include "producteditor.h" #include "purchaseeditor.h" #include "subcategoryeditor.h" #include "../../src/hash.h" #include "../../src/misc.h" #include "../../src/structs.h" #include "../../src/enums.h" #include "../../src/productdelegate.h" #include "offersdelegate.h" #include "../../dataAccess/azahar.h" #include "../../src/inputdialog.h" #include "../../mibitWidgets/mibitfloatpanel.h" #include "../../mibitWidgets/mibitnotifier.h" #include "../../printing/print-dev.h" #include "../../printing/print-cups.h" #include <QLabel> #include <QPixmap> #include <QByteArray> #include <QBuffer> #include <QTimer> #include <QDoubleValidator> #include <QRegExp> #include <QTableView> #include <QInputDialog> #include <QListWidgetItem> #include <QDataWidgetMapper> #include <QSqlRelationalTableModel> #include <QSqlRelationalDelegate> #include <QItemDelegate> #include <QHeaderView> #include <QDir> #include <klocale.h> #include <kfiledialog.h> #include <kiconloader.h> #include <kmessagebox.h> #include <kactioncollection.h> #include <kaction.h> #include <kstandarddirs.h> #include <kplotobject.h> #include <kplotwidget.h> #include <kplotaxis.h> #include <kplotpoint.h> #include <KNotification> //TODO: Change all qDebug to errorDialogs or remove them. //NOTE: Common configuration fields need to be shared between iotpos and iotstock (low stock alarm value). enum {pWelcome=0, pBrowseProduct=1, pBrowseOffers=2, pBrowseUsers=3, pBrowseMeasures=4, pBrowseCategories=5, pBrowseClients=6, pBrowseRandomMessages=7, pBrowseLogs=8, pBrowseSO=9, pReports=10, pBrowseCurrencies=11, pBrowseReservations=12, pBrowseSubCategories=14, pBrowseDepartments=15}; iotstockView::iotstockView(QWidget *parent) : QWidget(parent) { qDebug()<<"===STARTING IOTSTOCK AT "<<QDateTime::currentDateTime().toString()<<" ==="; adminIsLogged = false; ui_mainview.setupUi(this); setAutoFillBackground(true); // The db = QSqlDatabase called multiple times is causing a crash on certain installations (Not on kubuntu 8.10). QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8")); db = QSqlDatabase::addDatabase("QMYSQL"); ///Login dialog dlgPassword = new LoginWindow(i18n("Authorisation Required"), i18n("Enter administrator/supervisor user and password please."), LoginWindow::PasswordOnly); ui_mainview.headerLabel->setText(i18n("Basic Information")); ui_mainview.headerImg->setPixmap((DesktopIcon("view-statistics", 22))); ///other things counter = 5; modelsCreated = false; graphSoldItemsCreated = false; timerCheckDb = new QTimer(this); timerCheckDb->setInterval(1000); timerUpdateGraphs = new QTimer(this); timerUpdateGraphs->setInterval(10000); categoriesHash.clear(); subcategoriesHash.clear(); departmentsHash.clear(); setupSignalConnections(); QTimer::singleShot(1100, this, SLOT(setupDb())); QTimer::singleShot(2000, timerCheckDb, SLOT(start())); QTimer::singleShot(20000, timerUpdateGraphs, SLOT(start())); QTimer::singleShot(2010, this, SLOT(showWelcomeGraphs())); QTimer::singleShot(2000, this, SLOT(login())); //aquimeme rmTimer = new QTimer(this); connect(rmTimer, SIGNAL(timeout()), SLOT(reSelectModels()) ); rmTimer->start(1000*60*2); ui_mainview.stackedWidget->setCurrentIndex(pWelcome); ui_mainview.errLabel->hide(); ui_mainview.productsViewAlt->hide(); QString logoBottomFile = KStandardDirs::locate("appdata", "images/logo.png"); ui_mainview.logoLabel->setPixmap(QPixmap(logoBottomFile)); ui_mainview.logoLabel->setAlignment(Qt::AlignCenter); itmEndOfDay = new QListWidgetItem(DesktopIcon("iotpos-reports", 96), i18n("End of Day"), ui_mainview.reportsList); itmGralEndOfDay = new QListWidgetItem(DesktopIcon("iotpos-reports", 96), i18n("General End of Day"), ui_mainview.reportsList); itmEndOfMonth = new QListWidgetItem(DesktopIcon("iotpos-reports", 96), i18n("End of Month"), ui_mainview.reportsList); itmPrintSoldOutProducts = new QListWidgetItem(DesktopIcon("iotpos-reports", 96), i18n("Sold Out Products"), ui_mainview.reportsList); itmPrintLowStockProducts = new QListWidgetItem(DesktopIcon("iotpos-reports", 96), i18n("Low Stock Products"), ui_mainview.reportsList); itmPrintStock = new QListWidgetItem(DesktopIcon("iotpos-reports", 96), i18n("Stock Report"), ui_mainview.reportsList); //itmPrintBalance = new QListWidgetItem(DesktopIcon("iotpos-reports", 96), i18n("A Balance"), ui_mainview.reportsList); ui_mainview.btnBalances->setIcon(DesktopIcon("iotposbalance", 22)); ui_mainview.btnCashFlow->setIcon(DesktopIcon("iotpos-cashout", 22)); ui_mainview.btnTransactions->setIcon(DesktopIcon("wallet-open", 22)); ui_mainview.btnSO->setIcon(DesktopIcon("iotpos-box", 22)); QTimer::singleShot(500,this, SLOT(createFloatingPanels()) ); QTimer::singleShot(1000,this, SLOT(checkDefaultView()) ); logoBottomFile = KStandardDirs::locate("appdata", "styles/"); logoBottomFile = logoBottomFile+"tip.svg"; notifierPanel = new MibitNotifier(this,logoBottomFile, DesktopIcon("dialog-warning", 22)); } void iotstockView::checkDefaultView() { if (Settings::isProductsGridDefault()) { ui_mainview.productsView->show(); ui_mainview.productsViewAlt->hide(); ui_mainview.chViewProductsListAsGrid->setChecked(true); } else { ui_mainview.productsView->hide(); ui_mainview.productsViewAlt->show(); fpFilterProducts->reParent(ui_mainview.productsViewAlt); ui_mainview.chViewProductsListAsTable->setChecked(true); } } void iotstockView::createFloatingPanels() { QString path = KStandardDirs::locate("appdata", "styles/"); path = path+"floating_top.svg"; fpFilterTrans = new MibitFloatPanel(ui_mainview.transactionsTable, path, Top,460,300); fpFilterProducts = new MibitFloatPanel(ui_mainview.productsView, path, Top,460,200); fpFilterOffers = new MibitFloatPanel(ui_mainview.tableBrowseOffers, path, Top,500,200); fpFilterBalances = new MibitFloatPanel(ui_mainview.balancesTable, path, Top,460,240); fpFilterSpecialOrders = new MibitFloatPanel(ui_mainview.tableSO, path, Top,460,240); fpFilterTrans->addWidget(ui_mainview.groupFilterTransactions); fpFilterProducts->addWidget(ui_mainview.groupFilterProducts); fpFilterBalances->addWidget(ui_mainview.groupFilterBalances); fpFilterOffers->addWidget(ui_mainview.groupFilterOffers); fpFilterSpecialOrders->addWidget(ui_mainview.groupSOFilter); } void iotstockView::cleanErrorLabel() { ui_mainview.errLabel->clear(); ui_mainview.errLabel->hide(); } void iotstockView::login(){ qDebug()<<"Login()"; adminIsLogged = false; loggedUserId = 0; disableUI(); emit signalAdminLoggedOff(); dlgPassword->clearLines(); if (!db.isOpen()) { db.open(); //try to open connection qDebug()<<"(1): Trying to open connection to database.."; } if (!db.isOpen()) { QString details = db.lastError().text(); //KPassivePopup::message( i18n("Error:"),details, DesktopIcon("dialog-error", 22), this ); KNotification *notify = new KNotification(i18n("Unable to connect to the database"), this); notify->setText(details); QPixmap pixmap = DesktopIcon("dialog-error",22); //NOTE: This does not works notify->setPixmap(pixmap); notify->sendEvent(); emit signalShowDbConfig(); } else { bool doit = false; if (!Settings::lowSecurityMode()) { doit = dlgPassword->exec(); } else { //this is a low security mode! adminIsLogged = true; loggedUserId = 1; //default admin. emit signalAdminLoggedOn(); enableUI(); } if ( doit ) { int role = dlgPassword->getUserRole(); loggedUserId = dlgPassword->getUserId(); if ( role == roleAdmin) { adminIsLogged = true; emit signalAdminLoggedOn(); qDebug()<<"Admin Logged on.."; } else if (role == roleSupervisor) { adminIsLogged = false; emit signalSupervisorLoggedOn(); qDebug()<<"Supervisor Logged on.."; } else { emit signalAdminLoggedOff(); adminIsLogged = false; } enableUI(); } else { //restrict only if NOT low sec mode if (!Settings::lowSecurityMode()) { emit signalAdminLoggedOff(); loggedUserId = 0; disableUI(); qDebug()<<"login cancelled..."; } } } } void iotstockView::setupSignalConnections() { //NOTE: Use activated or double clicked??? sometimes doubleclicked does not work! by using activated and setting "double clicks activate" on // kde systemsettings preference dialog (mose and keyboard config) is fine for iotstock, but not for iotpos using a touchscreen. In this // last case, it make sense to let "single click activates" setting on kde systemsettings since is rarely used iotpos and iotstock in the same pc. connect(ui_mainview.usersView, SIGNAL(activated(const QModelIndex &)), SLOT(usersViewOnSelected(const QModelIndex &))); connect(ui_mainview.clientsView, SIGNAL(activated(const QModelIndex &)), SLOT(clientsViewOnSelected(const QModelIndex &))); connect(ui_mainview.productsView, SIGNAL(activated(const QModelIndex &)), SLOT(productsViewOnSelected(const QModelIndex &))); connect(ui_mainview.productsViewAlt, SIGNAL(activated(const QModelIndex &)), SLOT(productsViewOnSelected(const QModelIndex &))); connect(ui_mainview.tableReservations, SIGNAL(activated(const QModelIndex &)), SLOT(reservationsOnSelected(const QModelIndex &))); connect(ui_mainview.tableReservations, SIGNAL(entered(const QModelIndex &)), SLOT(reservationsOnSelected(const QModelIndex &))); ui_mainview.tableReservations->setMouseTracking(true); //to allow the entered signal works on the previous line. connect(ui_mainview.tableDepartments, SIGNAL(activated(const QModelIndex &)), SLOT(departmentsOnSelected(const QModelIndex &))); connect(ui_mainview.tableCategories, SIGNAL(activated(const QModelIndex &)), SLOT(categoriesOnSelected(const QModelIndex &))); connect(ui_mainview.groupFilterOffers, SIGNAL(toggled(bool)), SLOT(setOffersFilter())); connect(ui_mainview.chOffersSelectDate, SIGNAL(toggled(bool)), SLOT(setOffersFilter())); connect(ui_mainview.chOffersTodayDiscounts, SIGNAL(toggled(bool)), SLOT(setOffersFilter())); connect(ui_mainview.chOffersOldDiscounts, SIGNAL(toggled(bool)), SLOT(setOffersFilter())); connect(ui_mainview.chOffersFilterByProduct, SIGNAL(toggled(bool)), SLOT(setOffersFilter())); connect(ui_mainview.editOffersFilterByProduct, SIGNAL( textEdited(const QString &) ), SLOT(setOffersFilter())); connect(ui_mainview.btnAddUser, SIGNAL(clicked()), SLOT(createUser())); connect(ui_mainview.btnAddOffer, SIGNAL(clicked()), SLOT(createOffer())); connect(ui_mainview.btnDeleteUser, SIGNAL(clicked()), SLOT(deleteSelectedUser())); connect(ui_mainview.btnDeleteOffer, SIGNAL(clicked()), SLOT(deleteSelectedOffer())); connect(ui_mainview.btnAddProduct, SIGNAL(clicked()), SLOT(createProduct()) ); connect(ui_mainview.btnAddMeasure, SIGNAL(clicked()), SLOT(createMeasure()) ); connect(ui_mainview.btnAddDepartment, SIGNAL(clicked()), SLOT(createDepartment()) ); connect(ui_mainview.btnAddCategory, SIGNAL(clicked()), SLOT(createCategory()) ); connect(ui_mainview.btnAddSubCategory, SIGNAL(clicked()), SLOT(createSubCategory()) ); connect(ui_mainview.btnAddClient, SIGNAL(clicked()), SLOT(createClient())); connect(ui_mainview.btnDeleteProduct, SIGNAL(clicked()), SLOT(deleteSelectedProduct()) ); connect(ui_mainview.btnDeleteMeasure, SIGNAL(clicked()), SLOT(deleteSelectedMeasure()) ); connect(ui_mainview.btnDeleteDepartment, SIGNAL(clicked()), SLOT(deleteSelectedDepartment()) ); connect(ui_mainview.btnDeleteCategory, SIGNAL(clicked()), SLOT(deleteSelectedCategory()) ); connect(ui_mainview.btnDeleteSubCategory, SIGNAL(clicked()), SLOT(deleteSelectedSubCategory()) ); connect(ui_mainview.btnDeleteClient, SIGNAL(clicked()), SLOT(deleteSelectedClient())); //connect(ui_mainview.btnConfigure, SIGNAL(clicked()), SLOT( showPrefs())); connect(ui_mainview.btnAddRandomMsg, SIGNAL(clicked()), SLOT(createRandomMsg())); connect(timerCheckDb, SIGNAL(timeout()), this, SLOT(checkDBStatus())); connect(timerUpdateGraphs, SIGNAL(timeout()), this, SLOT(updateGraphs())); connect(ui_mainview.offersDateEditor, SIGNAL(changed(const QDate &)), this, SLOT(setOffersFilter())); connect(this, SIGNAL(signalAdminLoggedOn()), SLOT( enableUI())); connect(this, SIGNAL(signalAdminLoggedOff()), SLOT( disableUI())); //connect(ui_mainview.btnExit, SIGNAL(clicked()), SLOT( doEmitSignalSalir())); connect(ui_mainview.chViewProductsListAsGrid, SIGNAL(toggled(bool)), SLOT(showProdListAsGrid())); connect(ui_mainview.chViewProductsListAsTable, SIGNAL(toggled(bool)), SLOT(showProdListAsTable() )); //connect actions for transactions filters connect(ui_mainview.groupFilterTransactions, SIGNAL(toggled(bool)), this, SLOT( setTransactionsFilter()) ); connect(ui_mainview.rbTransFilterByStateFinished, SIGNAL(toggled(bool)), this, SLOT( setTransactionsFilter()) ); connect(ui_mainview.rbTransFilterByStateCancelled, SIGNAL(toggled(bool)), this, SLOT( setTransactionsFilter()) ); connect(ui_mainview.rbTransFilterByPaidCash, SIGNAL(toggled(bool)), this, SLOT( setTransactionsFilter()) ); connect(ui_mainview.rbTransFilterByPaidCredit, SIGNAL(toggled(bool)), this, SLOT( setTransactionsFilter()) ); connect(ui_mainview.comboCardTypes, SIGNAL(currentIndexChanged(int)), this, SLOT( setTransactionsFilter()) ); connect(ui_mainview.rbTransFilterByDate, SIGNAL(toggled(bool)), this, SLOT( setTransactionsFilter()) ); connect(ui_mainview.transactionsDateEditor, SIGNAL( changed(const QDate &) ), SLOT(setTransactionsFilter())); connect(ui_mainview.rbTransFilterByUser, SIGNAL(toggled(bool)), this, SLOT( setTransactionsFilter()) ); connect(ui_mainview.editTransUsersFilter,SIGNAL(textEdited( const QString &)), this, SLOT( setTransactionsFilter()) ); connect(ui_mainview.rbTransFilterByClient, SIGNAL(toggled(bool)), this, SLOT( setTransactionsFilter()) ); connect(ui_mainview.editTransClientsFilter,SIGNAL(textEdited( const QString &)), this, SLOT( setTransactionsFilter()) ); connect(ui_mainview.rbTransFilterByAmountLess, SIGNAL(toggled(bool)), this, SLOT( setTransactionsFilter()) ); connect(ui_mainview.rbTransFilterByAmountGreater, SIGNAL(toggled(bool)), this, SLOT( setTransactionsFilter()) ); connect(ui_mainview.editTransAmountLess ,SIGNAL(valueChanged ( double ) ), this, SLOT( setTransactionsFilter()) ); connect(ui_mainview.editTransAmountGreater,SIGNAL(valueChanged ( double ) ), this, SLOT( setTransactionsFilter()) ); connect(ui_mainview.rbTransFilterTerminalNum, SIGNAL(toggled(bool)), this, SLOT( setTransactionsFilter()) ); connect(ui_mainview.editTransTermNum,SIGNAL(valueChanged ( int ) ), this, SLOT( setTransactionsFilter()) ); connect(ui_mainview.rbTransactionsFilterOnlySales, SIGNAL(toggled(bool)), this, SLOT( setTransactionsFilter()) ); connect(ui_mainview.rbTransactionsFilterOnlyPurchases, SIGNAL(toggled(bool)), this, SLOT( setTransactionsFilter()) ); connect(ui_mainview.rbTransactionsFilterOnlyChangesReturns, SIGNAL(toggled(bool)), this, SLOT( setTransactionsFilter()) ); //connect actions for balances filters connect(ui_mainview.groupFilterBalances, SIGNAL(toggled(bool)), this, SLOT( setBalancesFilter()) ); connect(ui_mainview.rbBalancesFilterByState, SIGNAL(toggled(bool)), this, SLOT( setBalancesFilter()) ); connect(ui_mainview.rbBalancesFilterBySuspicious, SIGNAL(toggled(bool)), this, SLOT( setBalancesFilter()) ); connect(ui_mainview.rbBalancesFilterByDate, SIGNAL(toggled(bool)), this, SLOT( setBalancesFilter()) ); connect(ui_mainview.rbBalancesFilterByUser, SIGNAL(toggled(bool)), this, SLOT( setBalancesFilter()) ); connect(ui_mainview.rbBalancesFilterByCashInLess, SIGNAL(toggled(bool)), this, SLOT( setBalancesFilter()) ); connect(ui_mainview.rbBalancesFilterByCashInGrater, SIGNAL(toggled(bool)), this, SLOT( setBalancesFilter()) ); connect(ui_mainview.editBalancesFilterByDate, SIGNAL( changed(const QDate &) ), SLOT(setBalancesFilter())); connect(ui_mainview.rbBalancesFilgerByTerminalNum, SIGNAL(toggled(bool)), this, SLOT( setBalancesFilter()) ); connect(ui_mainview.editBalancesFilterByVendor,SIGNAL(textEdited( const QString &)), this, SLOT( setBalancesFilter()) ); connect(ui_mainview.editBalancesFilterByCasInLess ,SIGNAL(valueChanged ( double ) ), this, SLOT( setBalancesFilter()) ); connect(ui_mainview.editBalancesFilterByCashInGrater,SIGNAL(valueChanged ( double ) ), this, SLOT( setBalancesFilter()) ); connect(ui_mainview.editBalancesFilterByTermNum,SIGNAL(valueChanged ( int ) ), this, SLOT( setBalancesFilter()) ); connect(ui_mainview.btnPrintBalance, SIGNAL(clicked()) ,SLOT(printSelectedBalance()) ); connect(ui_mainview.comboProductsFilterByCategory,SIGNAL(currentIndexChanged(int)), this, SLOT( setProductsFilter()) ); connect(ui_mainview.editProductsFilterByDesc,SIGNAL(textEdited(const QString &)), this, SLOT( setProductsFilter()) ); connect(ui_mainview.rbProductsFilterByDesc, SIGNAL(toggled(bool)), this, SLOT( setProductsFilter()) ); connect(ui_mainview.rbProductsFilterByCategory, SIGNAL(toggled(bool)), this, SLOT( setProductsFilter()) ); connect(ui_mainview.rbProductsFilterByAvailable, SIGNAL(toggled(bool)), this, SLOT( setProductsFilter()) ); connect(ui_mainview.rbProductsFilterByNotAvailable, SIGNAL(toggled(bool)), this, SLOT( setProductsFilter()) ); connect(ui_mainview.rbProductsFilterByMostSold, SIGNAL(toggled(bool)), this, SLOT( setProductsFilter()) ); connect(ui_mainview.rbProductsFilterByLessSold, SIGNAL(toggled(bool)), this, SLOT( setProductsFilter()) ); connect(ui_mainview.rbProductsFilterByAlmostSoldOut, SIGNAL(toggled(bool)), this, SLOT( setProductsFilter()) ); connect(ui_mainview.rbProductsFilterByRaw, SIGNAL(toggled(bool)), this, SLOT( setProductsFilter()) ); connect(ui_mainview.rbProductsFilterByGroup, SIGNAL(toggled(bool)), this, SLOT( setProductsFilter()) ); connect(ui_mainview.groupFilterProducts, SIGNAL(toggled(bool)), this, SLOT( setProductsFilter()) ); connect(ui_mainview.comboProductsFilterBySubCategory,SIGNAL(currentIndexChanged(int)), this, SLOT( setProductsFilter()) ); connect(ui_mainview.rbProductsFilterBySubCategory, SIGNAL(toggled(bool)), this, SLOT( setProductsFilter()) ); connect(ui_mainview.chChainiedFilterForCategories, SIGNAL(toggled(bool)), this, SLOT( setProductsFilter()) ); // BFB: New, export qtableview connect(ui_mainview.btnExport, SIGNAL(clicked()), SLOT( exportTable())); connect(ui_mainview.btnExportProducts, SIGNAL(clicked()), SLOT( exportTable())); connect(ui_mainview.btnExportOffers, SIGNAL(clicked()), SLOT( exportTable())); connect(ui_mainview.btnExportUsers, SIGNAL(clicked()), SLOT( exportTable())); connect(ui_mainview.btnExportClients, SIGNAL(clicked()), SLOT( exportTable())); connect(ui_mainview.btnExportMeasures, SIGNAL(clicked()), SLOT( exportTable())); connect(ui_mainview.btnExportCategories, SIGNAL(clicked()), SLOT( exportTable())); connect(ui_mainview.btnExportSubCategories, SIGNAL(clicked()), SLOT( exportTable())); //connect(ui_mainview.btnExportCustomReports, SIGNAL(clicked()), SLOT( exportTable())); //connect(ui_mainview.btnLogin, SIGNAL(clicked()), this, SLOT(login())); connect(ui_mainview.btnBalances, SIGNAL(clicked()), SLOT(showBalancesPage())); connect(ui_mainview.btnTransactions, SIGNAL(clicked()), SLOT(showTransactionsPage())); connect(ui_mainview.btnCashFlow, SIGNAL(clicked()), SLOT(showCashFlowPage())); connect(ui_mainview.btnSO, SIGNAL(clicked()), SLOT(showSpecialOrders())); connect(ui_mainview.reportsList, SIGNAL(itemActivated(QListWidgetItem *)), SLOT(reportActivated(QListWidgetItem *))); //connect actions for special orders filters connect(ui_mainview.groupSOFilter, SIGNAL(toggled(bool)), this, SLOT( setSpecialOrdersFilter()) ); connect(ui_mainview.rbSOByDate, SIGNAL(toggled(bool)), this, SLOT( setSpecialOrdersFilter()) ); connect(ui_mainview.rbSOByThisWeek, SIGNAL(toggled(bool)), this, SLOT( setSpecialOrdersFilter()) ); connect(ui_mainview.rbSOByThisMonth, SIGNAL(toggled(bool)), this, SLOT( setSpecialOrdersFilter()) ); connect(ui_mainview.rbSOByStatusPending, SIGNAL(toggled(bool)), this, SLOT( setSpecialOrdersFilter()) ); connect(ui_mainview.rbSOByStatusReady, SIGNAL(toggled(bool)), this, SLOT( setSpecialOrdersFilter()) ); connect(ui_mainview.rbSOByStatusDelivered, SIGNAL( toggled(bool) ), SLOT(setSpecialOrdersFilter())); connect(ui_mainview.rbSOByStatusCancelled, SIGNAL(toggled(bool)), this, SLOT( setSpecialOrdersFilter()) ); connect(ui_mainview.datePicker,SIGNAL(changed(const QDate &)), this, SLOT( setSpecialOrdersFilter()) ); connect(ui_mainview.btnAddCurrency, SIGNAL(clicked()), SLOT(createCurrency())); connect(ui_mainview.btnDeleteCurrency, SIGNAL(clicked()), SLOT(deleteSelectedCurrency())); } void iotstockView::doEmitSignalSalir() { emit signalSalir(); } void iotstockView::enableUI() { ui_mainview.stackedWidget->show(); } void iotstockView::disableUI() { ui_mainview.stackedWidget->hide(); } void iotstockView::showWelcomeGraphs() { if (!graphSoldItemsCreated) setupGraphs(); ui_mainview.stackedWidget->setCurrentIndex(pWelcome); ui_mainview.headerLabel->setText(i18n("Quick Information")); ui_mainview.headerImg->setPixmap((DesktopIcon("view-statistics",22))); ui_mainview.btnPrintBalance->hide(); } void iotstockView::showPrefs() { emit signalShowPrefs(); } void iotstockView::showProductsPage() { ui_mainview.stackedWidget->setCurrentIndex(pBrowseProduct); if (productsModel->tableName().isEmpty()) setupProductsModel(); ui_mainview.headerLabel->setText(i18n("Products")); ui_mainview.headerImg->setPixmap((DesktopIcon("iotpos-box",22))); ui_mainview.btnPrintBalance->hide(); QTimer::singleShot(200,this, SLOT(adjustProductsTable())); qDebug()<<"view ALT geometry:"<<ui_mainview.productsViewAlt->geometry()<<" NORM Geom:"<<ui_mainview.productsView->geometry(); QTimer::singleShot(500,fpFilterProducts, SLOT(fixPos())); } void iotstockView::showOffersPage() { ui_mainview.stackedWidget->setCurrentIndex(pBrowseOffers); if (offersModel->tableName().isEmpty()) setupOffersModel(); ui_mainview.headerLabel->setText(i18n("Offers")); ui_mainview.headerImg->setPixmap((DesktopIcon("iotpos-offers",22))); ui_mainview.offersDateEditor->setDate(QDate::currentDate()); QTimer::singleShot(500,this, SLOT(adjustOffersTable())); ui_mainview.btnPrintBalance->hide(); QTimer::singleShot(200,fpFilterOffers, SLOT(fixPos())); //FIXME & NOTE: Offers that does not have existing products are ignored (hidden) on the view, but still exists on Database. // This happens when an offer exists for a product, but the product code is changed or deleted later. } void iotstockView::showUsersPage() { ui_mainview.stackedWidget->setCurrentIndex(pBrowseUsers); if (usersModel->tableName().isEmpty()) setupUsersModel(); ui_mainview.headerLabel->setText(i18n("Vendors")); ui_mainview.headerImg->setPixmap((DesktopIcon("iotpos-user",22))); ui_mainview.btnPrintBalance->hide(); } void iotstockView::showMeasuresPage() { ui_mainview.stackedWidget->setCurrentIndex(pBrowseMeasures); if (measuresModel->tableName().isEmpty()) setupMeasuresModel(); ui_mainview.headerLabel->setText(i18n("Weight and Measures")); ui_mainview.headerImg->setPixmap((DesktopIcon("iotpos-ruler",22))); ui_mainview.btnPrintBalance->hide(); } void iotstockView::showDepartmentsPage() { ui_mainview.stackedWidget->setCurrentIndex(pBrowseDepartments); if (departmentsModel->tableName().isEmpty()) setupDepartmentsModel(); ui_mainview.headerLabel->setText(i18n("Departments")); ui_mainview.headerImg->setPixmap((DesktopIcon("iotpos-categories",22))); ui_mainview.btnPrintBalance->hide(); } void iotstockView::showCategoriesPage() { ui_mainview.stackedWidget->setCurrentIndex(pBrowseCategories); if (categoriesModel->tableName().isEmpty()) setupCategoriesModel(); ui_mainview.headerLabel->setText(i18n("Categories")); ui_mainview.headerImg->setPixmap((DesktopIcon("iotpos-categories",22))); ui_mainview.btnPrintBalance->hide(); } void iotstockView::showSubCategoriesPage() { ui_mainview.stackedWidget->setCurrentIndex(pBrowseSubCategories); if (subcategoriesModel->tableName().isEmpty()) setupSubCategoriesModel(); ui_mainview.headerLabel->setText(i18n("Subcategories")); ui_mainview.headerImg->setPixmap((DesktopIcon("iotpos-categories",22))); ui_mainview.btnPrintBalance->hide(); } void iotstockView::showClientsPage() { ui_mainview.stackedWidget->setCurrentIndex(pBrowseClients); if (clientsModel->tableName().isEmpty()) setupClientsModel(); ui_mainview.headerLabel->setText(i18n("Clients")); ui_mainview.headerImg->setPixmap((DesktopIcon("iotpos-user",22))); ui_mainview.btnPrintBalance->hide(); } void iotstockView::showTransactionsPage() { ui_mainview.stackedWidget->setCurrentIndex(pReports); ui_mainview.stackedWidget2->setCurrentIndex(1); if (transactionsModel->tableName().isEmpty()) setupTransactionsModel(); ui_mainview.headerLabel->setText(i18n("Transactions")); ui_mainview.headerImg->setPixmap((DesktopIcon("iotpos-reports",22))); ui_mainview.transactionsDateEditor->setDate(QDate::currentDate()); ui_mainview.btnPrintBalance->hide(); QTimer::singleShot(200,fpFilterTrans, SLOT(fixPos())); } void iotstockView::showBalancesPage() { ui_mainview.stackedWidget->setCurrentIndex(pReports); ui_mainview.stackedWidget2->setCurrentIndex(2); if (balancesModel->tableName().isEmpty()) setupBalancesModel(); ui_mainview.headerLabel->setText(i18n("Balances")); ui_mainview.headerImg->setPixmap((DesktopIcon("iotpos-balance",22))); ui_mainview.btnPrintBalance->show(); QTimer::singleShot(200,fpFilterBalances, SLOT(fixPos())); } void iotstockView::showSpecialOrders() { ui_mainview.stackedWidget->setCurrentIndex(pReports); ui_mainview.stackedWidget2->setCurrentIndex(3); if (specialOrdersModel->tableName().isEmpty()) setupSpecialOrdersModel(); ui_mainview.headerLabel->setText(i18n("Special Orders")); ui_mainview.headerImg->setPixmap((DesktopIcon("iotpos-box",22))); //FIXME: Create an icon QTimer::singleShot(200,fpFilterSpecialOrders, SLOT(fixPos())); ui_mainview.datePicker->setDate(QDate::currentDate()); } void iotstockView::showCashFlowPage() { ui_mainview.stackedWidget->setCurrentIndex(pReports); ui_mainview.stackedWidget2->setCurrentIndex(0); if (cashflowModel->tableName().isEmpty()) setupCashFlowModel(); ui_mainview.headerLabel->setText(i18n("Cash Flow")); ui_mainview.headerImg->setPixmap((DesktopIcon("iotpos-cashout",22))); ui_mainview.cashFlowTable->resizeColumnsToContents(); ui_mainview.btnPrintBalance->hide(); } void iotstockView::showReports() { ui_mainview.stackedWidget->setCurrentIndex(pReports); ui_mainview.headerLabel->setText(i18n("Reports")); ui_mainview.headerImg->setPixmap((DesktopIcon("iotpos-reports",22))); if (ui_mainview.stackedWidget2->currentIndex() == 2) ui_mainview.btnPrintBalance->show(); else ui_mainview.btnPrintBalance->hide(); } void iotstockView::showRandomMsgs() { ui_mainview.stackedWidget->setCurrentIndex(pBrowseRandomMessages); ui_mainview.headerLabel->setText(i18n("Ticket Messages")); ui_mainview.headerImg->setPixmap((DesktopIcon("iotpos-ticket",22))); if (randomMsgModel->tableName().isEmpty()) setupRandomMsgModel(); } void iotstockView::showCurrencies() { ui_mainview.stackedWidget->setCurrentIndex(pBrowseCurrencies); ui_mainview.headerLabel->setText(i18n("Currencies")); ui_mainview.headerImg->setPixmap((DesktopIcon("iotpos-money",22))); if (currenciesModel->tableName().isEmpty()) setupCurrenciesModel(); } void iotstockView::showReservations() { ui_mainview.stackedWidget->setCurrentIndex(pBrowseReservations);//TODO:Remember to change the page number when merging with 0.9.3rc2 ui_mainview.headerLabel->setText(i18n("Reservations")); ui_mainview.headerImg->setPixmap((DesktopIcon("iotpos-box",22))); if (reservationsModel->tableName().isEmpty()) setupReservationsModel(); } void iotstockView::toggleFilterBox(bool show) { if (show) { switch (ui_mainview.stackedWidget->currentIndex()) { case pBrowseProduct: ui_mainview.groupFilterProducts->show(); break; case pBrowseOffers:ui_mainview.groupFilterOffers->show(); break; case pWelcome: break; default: break; } } else { switch (ui_mainview.stackedWidget->currentIndex()) { case pBrowseProduct: ui_mainview.groupFilterProducts->hide(); break; case pBrowseOffers:ui_mainview.groupFilterOffers->hide(); break; case pWelcome: break; default: break; } } } void iotstockView::adjustProductsTable() { QSize size = ui_mainview.productsViewAlt->size(); int portion = size.width()/11; ui_mainview.productsViewAlt->horizontalHeader()->setResizeMode(QHeaderView::Interactive); ui_mainview.productsViewAlt->horizontalHeader()->resizeSection(0, portion*1.5); // CODE ui_mainview.productsViewAlt->horizontalHeader()->resizeSection(1, portion*3.5); //Name ui_mainview.productsViewAlt->horizontalHeader()->resizeSection(2, portion); //Price ui_mainview.productsViewAlt->horizontalHeader()->resizeSection(3, portion); //Stock ui_mainview.productsViewAlt->horizontalHeader()->resizeSection(4, portion); //Cost ui_mainview.productsViewAlt->horizontalHeader()->resizeSection(5, portion); //Sold Units ui_mainview.productsViewAlt->horizontalHeader()->resizeSection(6, portion); //Last Sold ui_mainview.productsViewAlt->horizontalHeader()->resizeSection(7, portion); //Category } void iotstockView::adjustOffersTable() { QSize size = ui_mainview.tableBrowseOffers->size(); int portion = size.width()/6; ui_mainview.tableBrowseOffers->horizontalHeader()->setResizeMode(QHeaderView::Interactive); ui_mainview.tableBrowseOffers->horizontalHeader()->resizeSection(1, portion*1.5); //PRODUCT DESC ui_mainview.tableBrowseOffers->horizontalHeader()->resizeSection(2, portion); //Qty ui_mainview.tableBrowseOffers->horizontalHeader()->resizeSection(3, portion); //Date start ui_mainview.tableBrowseOffers->horizontalHeader()->resizeSection(4, portion*2.5); //date end } void iotstockView::showProdListAsGrid() { if (ui_mainview.chViewProductsListAsGrid->isChecked()) { ui_mainview.productsView->show(); ui_mainview.productsViewAlt->hide(); //reparent the filter panel fpFilterProducts->reParent(ui_mainview.productsView); QTimer::singleShot(200,fpFilterProducts, SLOT(fixPos())); } } void iotstockView::showProdListAsTable() { if (ui_mainview.chViewProductsListAsTable->isChecked()) { ui_mainview.productsViewAlt->show(); ui_mainview.productsView->hide(); // BFB: There's no need to adjust product table. We could do a resizeColumnsToContents() after model.select() QTimer::singleShot(200,this, SLOT(adjustProductsTable())); //reparent the filter panel fpFilterProducts->reParent(ui_mainview.productsViewAlt); QTimer::singleShot(200,fpFilterProducts, SLOT(fixPos())); } } iotstockView::~iotstockView() { } void iotstockView::setupGraphs() { //plots... QString mes = (QDate::longMonthName(QDate::currentDate().month())).toUpper(); ui_mainview.plotSales->setMinimumSize( 200, 200 ); ui_mainview.plotSales->setAntialiasing( true ); objSales = new KPlotObject( Qt::yellow, KPlotObject::Bars, KPlotObject::Star); ui_mainview.plotSales->addPlotObject( objSales ); ui_mainview.plotSales->axis( KPlotWidget::BottomAxis )->setLabel( i18n("%1", mes) ); ui_mainview.plotSales->axis( KPlotWidget::LeftAxis )->setLabel( i18n("Month Sales (%1)", KGlobal::locale()->currencySymbol()) ); ui_mainview.plotProfit->setMinimumSize( 200, 200 ); ui_mainview.plotProfit->setAntialiasing( true ); objProfit = new KPlotObject( Qt::yellow, KPlotObject::Bars, KPlotObject::Star); ui_mainview.plotProfit->addPlotObject( objProfit ); ui_mainview.plotProfit->axis( KPlotWidget::BottomAxis )->setLabel( i18n("%1", mes) ); ui_mainview.plotProfit->axis( KPlotWidget::LeftAxis )->setLabel( i18n("Month Profit (%1)", KGlobal::locale()->currencySymbol()) ); ui_mainview.plotMostSold->setMinimumSize( 200, 200 ); ui_mainview.plotMostSold->setAntialiasing( true ); objMostSold = new KPlotObject( Qt::white, KPlotObject::Bars, KPlotObject::Star); objMostSoldB = new KPlotObject( Qt::green, KPlotObject::Bars, KPlotObject::Star); ui_mainview.plotMostSold->addPlotObject( objMostSold ); ui_mainview.plotMostSold->addPlotObject( objMostSoldB ); ui_mainview.plotMostSold->axis( KPlotWidget::BottomAxis )->setLabel( i18n("Products") ); ui_mainview.plotMostSold->axis( KPlotWidget::LeftAxis )->setLabel( i18n("Sold Units") ); objMostSold->setShowBars(true); objMostSold->setShowPoints(true); objMostSold->setShowLines(false); objMostSoldB->setShowBars(true); objMostSoldB->setShowPoints(true); objMostSoldB->setShowLines(false); ui_mainview.plotMostSold->setShowGrid(false); objMostSold->setBarBrush( QBrush( Qt::blue, Qt::SolidPattern ) ); objMostSold->setBarPen(QPen(Qt::white)); objMostSold->setPointStyle(KPlotObject::Star); objMostSoldB->setBarBrush( QBrush( Qt::darkYellow, Qt::SolidPattern ) ); objMostSoldB->setBarPen(QPen(Qt::white)); objMostSoldB->setPointStyle(KPlotObject::Star); objSales->setShowBars(true); objSales->setShowPoints(true); objSales->setShowLines(true); objSales->setLinePen( QPen( Qt::blue, 1.5, Qt::DashDotLine ) ); objSales->setBarBrush( QBrush( Qt::lightGray, Qt::Dense6Pattern ) ); objSales->setBarPen(QPen(Qt::lightGray)); objSales->setPointStyle(KPlotObject::Star); objProfit->setShowBars(true); objProfit->setShowPoints(true); objProfit->setShowLines(true); objProfit->setLinePen( QPen( Qt::blue, 1.5, Qt::DashDotLine ) ); objProfit->setBarBrush( QBrush( Qt::lightGray, Qt::Dense7Pattern ) ); objProfit->setBarPen(QPen(Qt::lightGray)); objProfit->setPointStyle(KPlotObject::Star); graphSoldItemsCreated = true; int y = (QApplication::desktop()->height()); if (y < 400){ ui_mainview.plotProfit->hide(); ui_mainview.plotMostSold->hide(); ui_mainview.frame->hide(); } updateGraphs(); } // UI and Database -- GRAPHS. void iotstockView::updateGraphs() { if (!db.isOpen()) openDB(); if (db.isOpen()) { if (!graphSoldItemsCreated ) setupGraphs(); else { Azahar *myDb = new Azahar(this); myDb->setDatabase(db); ///First we need to get data for the plots QList<TransactionInfo> monthTrans = myDb->getMonthTransactionsForPie(); ProfitRange rangeP = myDb->getMonthProfitRange(); ProfitRange rangeS = myDb->getMonthSalesRange(); //qDebug()<<"** [Ranges] Profit:"<<rangeP.min<<","<<rangeP.max<<" Sales:"<<rangeS.min<<","<<rangeS.max; TransactionInfo info; ///plots //clear data objSales->clearPoints(); objProfit->clearPoints(); // X = date, Y=profit int hoy=0; hoy = QDate::currentDate().day(); //NOTE:Set the same scale for both plots?? to compare.. or his own range to each one. if profit>sales? ui_mainview.plotSales->setLimits(0, hoy+1, rangeS.min-rangeS.min*.10, rangeS.max+rangeS.max*.10); ui_mainview.plotProfit->setLimits(0, hoy+1, rangeP.min-rangeS.min*.10, rangeP.max+rangeP.max*.10); //insert each day's sales and profit. int day=0; double AccSales=0.0; double AccProfit=0.0; //BEGIN Fix old issue. This is to fix the not shown values, the first and last days are not shown, fixed by adding day 0 and one after the last. objSales->addPoint(0,0, "0"); objProfit->addPoint(0,0, "0"); if (!monthTrans.isEmpty()) { TransactionInfo inf; inf.date = monthTrans.last().date.addDays(1); inf.amount = 0; inf.utility = 0; monthTrans.append(inf); } //END Fix old issue. for (int i = 0; i < monthTrans.size(); ++i) { info = monthTrans.at(i); ///we got one result per day (sum) //insert the day,profit to the plot AccSales = info.amount; AccProfit = info.utility; day = info.date.day(); objSales->addPoint(day,AccSales, QString::number(AccSales)); objProfit->addPoint(day,AccProfit, QString::number(AccProfit)); //qDebug()<<"ITERATING MONTH TRANSACTIONS | "<<day<<", sales:"<<info.amount<<" profit:"<<info.utility<<" AccSales:"<<AccSales<<" AccProfit:"<<AccProfit; } //for each eleement ui_mainview.plotSales->update(); ui_mainview.plotProfit->update(); //MOST SOLD PRODUCTS objMostSold->clearPoints(); objMostSoldB->clearPoints(); QList<pieProdInfo> plist = myDb->getTop5SoldProducts(); double maxPoint = myDb->getTopFiveMaximum(); if (maxPoint < 4 ) maxPoint = maxPoint+1; ui_mainview.plotMostSold->setLimits(0, 7, 0, maxPoint+maxPoint*.10); if (!plist.isEmpty()) { if (!graphSoldItemsCreated) setupGraphs(); else { int count = 0; foreach(pieProdInfo ppInfo, plist) { count++; objMostSold->addPoint(count, ppInfo.count, ppInfo.name); //if (count==2) objMostSoldB->addPoint(count, ppInfo.count, ppInfo.name); //qDebug()<<"# "<<count<<"product Count:"<<ppInfo.count<<" Name:"<<ppInfo.name; } //foreach objMostSold->addPoint(6,0,""); // workaround! }//else } //NOW ALMOST SOLD OUT PRODUCTS (top 5) maxPoint = myDb->getAlmostSoldOutMaximum(Settings::mostSoldMaxValue()); plist = myDb->getAlmostSoldOutProducts(Settings::mostSoldMaxValue()); if (!plist.isEmpty()) { if (!graphSoldItemsCreated) setupGraphs(); else { int count = 0; foreach(pieProdInfo ppInfo, plist) { count++; switch (count) { case 1: ui_mainview.lblProd1->setText(ppInfo.name+QString(" [%1]").arg(ppInfo.code)); ui_mainview.counter1->setText(QString::number(ppInfo.count)+" "+ppInfo.unitStr); break; case 2: ui_mainview.lblProd2->setText(ppInfo.name+QString(" [%1]").arg(ppInfo.code)); ui_mainview.counter2->setText(QString::number(ppInfo.count)+" "+ppInfo.unitStr); break; case 3: ui_mainview.lblProd3->setText(ppInfo.name+QString(" [%1]").arg(ppInfo.code)); ui_mainview.counter3->setText(QString::number(ppInfo.count)+" "+ppInfo.unitStr); break; case 4: ui_mainview.lblProd4->setText(ppInfo.name+QString(" [%1]").arg(ppInfo.code)); ui_mainview.counter4->setText(QString::number(ppInfo.count)+" "+ppInfo.unitStr); break; case 5: ui_mainview.lblProd5->setText(ppInfo.name+QString(" [%1]").arg(ppInfo.code)); ui_mainview.counter5->setText(QString::number(ppInfo.count)+" "+ppInfo.unitStr); break; } } //foreach }//else } //if not empty delete myDb; } } // if connected to db } /* ----------------- Database ----------------- */ void iotstockView::setupDb() { if (db.isOpen()) db.close(); db.setHostName(Settings::editDBServer()); db.setDatabaseName(Settings::editDBName()); db.setUserName(Settings::editDBUsername()); db.setPassword(Settings::editDBPassword()); db.open(); dlgPassword->setDb(db); if (db.isOpen()) { emit signalConnected(); enableUI(); //enable until logged in... productsModel = new QSqlRelationalTableModel(); offersModel = new QSqlRelationalTableModel(); usersModel = new QSqlTableModel(); measuresModel = new QSqlTableModel(); departmentsModel = new QSqlTableModel(); categoriesModel = new QSqlTableModel(); subcategoriesModel = new QSqlRelationalTableModel(); clientsModel = new QSqlTableModel(); transactionsModel = new QSqlRelationalTableModel(); balancesModel = new QSqlTableModel(); cashflowModel = new QSqlRelationalTableModel(); specialOrdersModel = new QSqlRelationalTableModel(); randomMsgModel = new QSqlTableModel(); logsModel = new QSqlRelationalTableModel(); reservationsModel = new QSqlRelationalTableModel(); currenciesModel = new QSqlTableModel(); modelsCreated = true; setupProductsModel(); setupMeasuresModel(); setupClientsModel(); setupUsersModel(); setupTransactionsModel(); setupCategoriesModel(); setupDepartmentsModel(); setupSubCategoriesModel(); setupOffersModel(); setupBalancesModel(); setupCashFlowModel(); setupSpecialOrdersModel(); setupRandomMsgModel(); setupLogsModel(); setupCurrenciesModel(); setupReservationsModel(); } else { emit signalDisconnected(); disableUI(); } } void iotstockView::openDB() { bool ok=false; if (!db.isOpen()) { ok = db.open(); } else ok = true; if (!ok) { emit signalDisconnected(); qDebug()<<db.lastError(); } else { emit signalConnected(); if (!modelsAreCreated()) setupDb(); } } void iotstockView::connectToDb() { if (!db.open()) { db.open(); //try to open connection qDebug()<<"(1/connectToDb) Trying to open connection to database.."; emit signalDisconnected(); disableUI(); } if (!db.isOpen()) { qDebug()<<"(2/connectToDb) Configuring.."; emit signalDisconnected(); disableUI(); } else { //finally, when connection stablished, setup all models. if (!modelsCreated) { //Create models... productsModel = new QSqlRelationalTableModel(); offersModel = new QSqlRelationalTableModel(); usersModel = new QSqlTableModel(); measuresModel = new QSqlTableModel(); categoriesModel = new QSqlTableModel(); departmentsModel = new QSqlTableModel(); subcategoriesModel = new QSqlRelationalTableModel(); clientsModel = new QSqlTableModel(); transactionsModel = new QSqlRelationalTableModel(); balancesModel = new QSqlTableModel(); cashflowModel = new QSqlRelationalTableModel(); specialOrdersModel = new QSqlRelationalTableModel(); randomMsgModel = new QSqlTableModel(); logsModel = new QSqlRelationalTableModel(); currenciesModel = new QSqlTableModel(); reservationsModel = new QSqlRelationalTableModel(); modelsCreated = true; } dlgPassword->setDb(db); emit signalConnected(); enableUI(); setupProductsModel(); setupMeasuresModel(); setupClientsModel(); setupUsersModel(); setupTransactionsModel(); setupCategoriesModel(); setupDepartmentsModel(); setupSubCategoriesModel(); setupOffersModel(); setupBalancesModel(); setupCashFlowModel(); setupSpecialOrdersModel(); setupRandomMsgModel(); setupLogsModel(); setupCurrenciesModel(); setupReservationsModel(); } } //NOTE:There is a problem if connected and then mysql stop... db.isOpen() returns true. void iotstockView::checkDBStatus() { if (!isConnected()) { if (counter < 4) { counter++; emit signalChangeStatusbar(i18n("Trying connection in %1 seconds...", 5-counter)); } else { counter = 0; emit signalChangeStatusbar(i18n("Connecting...")); openDB(); } } else emit signalChangeStatusbar(""); } void iotstockView::closeDB() { db.close(); } void iotstockView::setupUsersModel() { if (db.isOpen()) { usersModel->setTable("users"); ui_mainview.usersView->setModel(usersModel); ui_mainview.usersView->setViewMode(QListView::IconMode); ui_mainview.usersView->setGridSize(QSize(170,170)); ui_mainview.usersView->setEditTriggers(QAbstractItemView::NoEditTriggers); ui_mainview.usersView->setResizeMode(QListView::Adjust); ui_mainview.usersView->setModelColumn(usersModel->fieldIndex("photo")); ui_mainview.usersView->setSelectionMode(QAbstractItemView::SingleSelection); UsersDelegate *delegate = new UsersDelegate(ui_mainview.usersView); ui_mainview.usersView->setItemDelegate(delegate); usersModel->select(); } else { //At this point, what to do? // inform to the user about the error and finish app or retry again some time later? QString details = db.lastError().text(); KMessageBox::detailedError(this, i18n("Iotstock has encountered an error, click details to see the error details."), details, i18n("Error")); QTimer::singleShot(10000, this, SLOT(setupUsersModel())); } } void iotstockView::setupProductsModel() { openDB(); qDebug()<<"setupProducts.."; if (db.isOpen()) { productsModel->setTable("products"); productCodeIndex = productsModel->fieldIndex("code"); productDescIndex = productsModel->fieldIndex("name"); productPriceIndex= productsModel->fieldIndex("price"); productStockIndex= productsModel->fieldIndex("stockqty"); productCostIndex = productsModel->fieldIndex("cost"); productSoldUnitsIndex= productsModel->fieldIndex("soldunits"); productLastSoldIndex= productsModel->fieldIndex("datelastsold"); productUnitsIndex= productsModel->fieldIndex("units"); productTaxIndex = productsModel->fieldIndex("taxpercentage"); productETaxIndex= productsModel->fieldIndex("extrataxes"); productPhotoIndex=productsModel->fieldIndex("photo"); productCategoryIndex=productsModel->fieldIndex("category"); productPointsIndex=productsModel->fieldIndex("points"); productLastProviderIndex = productsModel->fieldIndex("lastproviderid"); productAlphaCodeIndex = productsModel->fieldIndex("alphacode"); productIsAGroupIndex = productsModel->fieldIndex("isAGroup"); productIsARawIndex = productsModel->fieldIndex("isARawProduct"); productIsNotDiscountable = productsModel->fieldIndex("isNotDiscountable"); productGEIndex = productsModel->fieldIndex("groupElements"); ui_mainview.productsView->setModel(productsModel); ui_mainview.productsView->setViewMode(QListView::IconMode); ui_mainview.productsView->setGridSize(QSize(128,128)); ui_mainview.productsView->setEditTriggers(QAbstractItemView::NoEditTriggers); ui_mainview.productsView->setResizeMode(QListView::Adjust); ui_mainview.productsView->setModelColumn(productsModel->fieldIndex("photo")); ui_mainview.productsViewAlt->setModel(productsModel); ui_mainview.productsViewAlt->setEditTriggers(QAbstractItemView::NoEditTriggers); ui_mainview.productsViewAlt->setSelectionMode(QAbstractItemView::SingleSelection); ui_mainview.productsViewAlt->setColumnHidden(productPhotoIndex, true); ui_mainview.productsViewAlt->setColumnHidden(productUnitsIndex, true); ui_mainview.productsViewAlt->setColumnHidden(productTaxIndex, true); ui_mainview.productsViewAlt->setColumnHidden(productETaxIndex, true); ui_mainview.productsViewAlt->setColumnHidden(productPointsIndex, true); ui_mainview.productsViewAlt->setColumnHidden(productGEIndex, true); ui_mainview.productsViewAlt->setColumnHidden(productIsAGroupIndex, true); ui_mainview.productsViewAlt->setColumnHidden(productIsARawIndex, true); ui_mainview.productsViewAlt->setColumnHidden(productIsNotDiscountable, true); /// 0.7 version : hidden next columns ui_mainview.productsViewAlt->setColumnHidden(productLastProviderIndex, true); ui_mainview.productsViewAlt->setColumnHidden(productAlphaCodeIndex, true); productsModel->setRelation(productCategoryIndex, QSqlRelation("categories", "catid", "text")); productsModel->setRelation(productLastProviderIndex, QSqlRelation("providers", "id", "name")); productsModel->setHeaderData(productCodeIndex, Qt::Horizontal, i18n("Code")); productsModel->setHeaderData(productDescIndex, Qt::Horizontal, i18n("Name")); productsModel->setHeaderData(productCategoryIndex, Qt::Horizontal, i18n("Category") ); productsModel->setHeaderData(productPriceIndex, Qt::Horizontal, i18n("Price") ); productsModel->setHeaderData(productCostIndex, Qt::Horizontal, i18n("Cost") ); productsModel->setHeaderData(productStockIndex, Qt::Horizontal, i18n("Stock Qty") ); productsModel->setHeaderData(productSoldUnitsIndex, Qt::Horizontal, i18n("Sold Units") ); productsModel->setHeaderData(productLastSoldIndex, Qt::Horizontal, i18n("Last Sold") ); productsModel->setHeaderData(productLastProviderIndex, Qt::Horizontal, i18n("Last Provider") ); productsModel->setHeaderData(productAlphaCodeIndex, Qt::Horizontal, i18n("Alpha Code") ); ProductDelegate *delegate = new ProductDelegate(ui_mainview.productsView); ui_mainview.productsView->setItemDelegate(delegate); ui_mainview.productsView->setSelectionMode(QAbstractItemView::SingleSelection); productsModel->select(); ui_mainview.productsViewAlt->resizeColumnsToContents(); //populate Categories... populateCategoriesHash(); populateSubCategoriesHash(); populateDepartmentsHash(); ui_mainview.comboProductsFilterByCategory->clear(); ui_mainview.comboProductsFilterBySubCategory->clear(); ui_mainview.comboProductsFilterByDepartment->clear(); QHashIterator<QString, int> item(categoriesHash); while (item.hasNext()) { item.next(); ui_mainview.comboProductsFilterByCategory->addItem(item.key()); } ui_mainview.comboProductsFilterByCategory->setCurrentIndex(0); //populate SubCategories... QHashIterator<QString, int> itemS(subcategoriesHash); while (itemS.hasNext()) { itemS.next(); ui_mainview.comboProductsFilterBySubCategory->addItem(itemS.key()); } ui_mainview.comboProductsFilterBySubCategory->setCurrentIndex(0); QHashIterator<QString, int> itemD(departmentsHash); while (itemD.hasNext()) { itemD.next(); ui_mainview.comboProductsFilterByDepartment->addItem(itemD.key()); } ui_mainview.comboProductsFilterByDepartment->setCurrentIndex(0); ui_mainview.rbProductsFilterByAvailable->setChecked(true); ui_mainview.productsViewAlt->setCurrentIndex(productsModel->index(0, 0)); setProductsFilter(); } qDebug()<<"setupProducts.. done."; } void iotstockView::populateDepartmentsHash() { Azahar *myDb = new Azahar; myDb->setDatabase(db); departmentsHash.clear(); departmentsHash = myDb->getDepartmentsHash(); delete myDb; } void iotstockView::populateCategoriesHash() { Azahar *myDb = new Azahar; myDb->setDatabase(db); categoriesHash.clear(); categoriesHash = myDb->getCategoriesHash(); delete myDb; } void iotstockView::populateCardTypesHash() { Azahar *myDb = new Azahar; myDb->setDatabase(db); cardTypesHash.clear(); cardTypesHash = myDb->getCardTypesHash(); delete myDb; } void iotstockView::populateSubCategoriesHash() { Azahar *myDb = new Azahar; myDb->setDatabase(db); subcategoriesHash.clear(); subcategoriesHash = myDb->getSubCategoriesHash(); delete myDb; } void iotstockView::setProductsFilter() { //NOTE: This is a QT BUG. // If filter by description is selected and the text is empty, and later is re-filtered // then NO pictures are shown; even if is refiltered again. QRegExp regexp = QRegExp(ui_mainview.editProductsFilterByDesc->text()); if (!ui_mainview.groupFilterProducts->isChecked()) productsModel->setFilter(""); else { if (ui_mainview.rbProductsFilterByDesc->isChecked()) { //1st if: Filter by DESC. if (!regexp.isValid()) ui_mainview.editProductsFilterByDesc->setText(""); if (ui_mainview.editProductsFilterByDesc->text()=="*" || ui_mainview.editProductsFilterByDesc->text()=="") productsModel->setFilter(""); else productsModel->setFilter(QString("products.name REGEXP '%1'").arg(ui_mainview.editProductsFilterByDesc->text())); productsModel->setSort(productStockIndex, Qt::DescendingOrder); } else if (ui_mainview.rbProductsFilterByAvailable->isChecked()) { //3rd if: filter by Available items productsModel->setFilter(QString("products.stockqty>0")); productsModel->setSort(productStockIndex, Qt::DescendingOrder); } else if (ui_mainview.rbProductsFilterByNotAvailable->isChecked()) { //4th if: filter by NOT Available items productsModel->setFilter(QString("products.stockqty=0")); productsModel->setSort(productSoldUnitsIndex, Qt::DescendingOrder); } else if (ui_mainview.rbProductsFilterByMostSold->isChecked()) { //5th if: filter by Most Sold items productsModel->setFilter(""); productsModel->setSort(productSoldUnitsIndex, Qt::DescendingOrder); } else if (ui_mainview.rbProductsFilterByAlmostSoldOut->isChecked()) { //6th if: filter by ALMOST sold-out items productsModel->setFilter(QString("products.stockqty<%1 AND products.stockqty>0").arg(Settings::mostSoldMaxValue())); productsModel->setSort(productSoldUnitsIndex, Qt::AscendingOrder); } else if (ui_mainview.rbProductsFilterByRaw->isChecked()) { //7th if: filter by raw products productsModel->setFilter(QString("products.isARawProduct=true")); productsModel->setSort(productCodeIndex, Qt::AscendingOrder); } else if (ui_mainview.rbProductsFilterByGroup->isChecked()) { //8th if: filter by GROUPS productsModel->setFilter(QString("products.isAGroup=true")); productsModel->setSort(productCodeIndex, Qt::AscendingOrder); } else if (ui_mainview.rbProductsFilterByLessSold->isChecked()) { //else: filter by less sold items productsModel->setFilter(""); productsModel->setSort(productSoldUnitsIndex, Qt::AscendingOrder); } else { //if (ui_mainview.rbProductsFilterByDepartment->isChecked()) { //Filter by DEPARTMENT/CATEGORY/SUBCATEGORY qDebug()<<"Last check, Department/Category/Subcategory filter"; bool chained = ui_mainview.chChainiedFilterForCategories->isChecked(); bool depChecked = ui_mainview.rbProductsFilterByDepartment->isChecked(); bool catChecked = ui_mainview.rbProductsFilterByCategory->isChecked(); //NOTE:NOT NEEDED. bool subChecked = ui_mainview.rbProductsFilterBySubCategory->isChecked(); //Find catId for the text on the combobox. int depId=-1; int catId=-1; int subCatId=-1; QString depText = ui_mainview.comboProductsFilterByDepartment->currentText(); QString catText = ui_mainview.comboProductsFilterByCategory->currentText(); QString subCatText = ui_mainview.comboProductsFilterBySubCategory->currentText(); //enable/disable the chainedFilter checkbox (only allow on dep/cat checkbox is checked; subcat does not has children. ui_mainview.chChainiedFilterForCategories->setEnabled( depChecked || catChecked ); if (categoriesHash.contains(catText)) catId = categoriesHash.value(catText); if (departmentsHash.contains(depText)) depId = departmentsHash.value(depText); if (subcategoriesHash.contains(subCatText)) subCatId = subcategoriesHash.value(subCatText); QString qryStr; //check if chained filter for dep/cat/subcat is checked. Then we will AND the query filter. if (chained) { //if department is checked then chain dep->cat->subcat if (depChecked) qryStr = QString("products.department=%1 AND products.category=%2 AND products.subcategory=%3").arg(depId).arg(catId).arg(subCatId); //if category is checked then chain cat->subcat else if (catChecked) qryStr = QString("products.category=%1 and products.subcategory=%2").arg(catId).arg(subCatId); //if subcat is checked then nothing is chained (subcat has no children) else qryStr = QString("products.category=%1").arg(catId); } //if chained filters else { if (depChecked) qryStr = QString("products.department=%1").arg(depId); else if (catChecked) qryStr = QString("products.category=%1").arg(catId); else qryStr = QString("products.subcategory=%1").arg(subCatId); }// no chained filters.. check only the selected one. qDebug()<<"Setting Filter:"<<qryStr; productsModel->setFilter(qryStr); productsModel->setSort(productStockIndex, Qt::DescendingOrder); } //filter by category //enable/disable the chainedFilter checkbox (only allow on dep/cat checkbox is checked; subcat does not has children. bool depChecked = ui_mainview.rbProductsFilterByDepartment->isChecked(); bool catChecked = ui_mainview.rbProductsFilterByCategory->isChecked(); ui_mainview.chChainiedFilterForCategories->setEnabled( depChecked || catChecked ); productsModel->select(); } } void iotstockView::setupOffersModel() { offersModel->setTable("offers"); offersModel->setEditStrategy(QSqlTableModel::OnFieldChange); offerIdIndex = offersModel->fieldIndex("id"); offerProdIdIndex = offersModel->fieldIndex("product_id"); offerDiscountIndex = offersModel->fieldIndex("discount"); offerDateStartIndex= offersModel->fieldIndex("datestart"); offerDateEndIndex = offersModel->fieldIndex("dateend"); offersModel->setRelation(offerProdIdIndex, QSqlRelation("products", "code", "name")); offersModel->setHeaderData(offerIdIndex, Qt::Horizontal, i18n("Id")); offersModel->setHeaderData(offerProdIdIndex, Qt::Horizontal, i18n("Product Affected")); offersModel->setHeaderData(offerDiscountIndex, Qt::Horizontal, i18n("Discount Applied (%)") ); offersModel->setHeaderData(offerDateStartIndex, Qt::Horizontal, i18n("Valid from") ); offersModel->setHeaderData(offerDateEndIndex, Qt::Horizontal, i18n("Valid until") ); ui_mainview.tableBrowseOffers->setModel(offersModel); //QSqlRelationalDelegate *itemOffersDelegate = new QSqlRelationalDelegate(ui_mainview.tableBrowseOffers); OffersDelegate *itemOffersDelegate = new OffersDelegate(ui_mainview.tableBrowseOffers); ui_mainview.tableBrowseOffers->setItemDelegate(itemOffersDelegate); ui_mainview.tableBrowseOffers->setColumnHidden(offerIdIndex, true); offersModel->select(); setOffersFilter(); ui_mainview.tableBrowseOffers->setSelectionMode(QAbstractItemView::SingleSelection); // connect(ui_mainview.tableBrowseOffers->selectionModel(), SIGNAL(currentRowChanged(QModelIndex,QModelIndex)), // this, SLOT(offersTableSelectionChanged(QModelIndex))); // connect(ui_mainview.tableBrowseOffers->horizontalHeader(), SIGNAL(sectionClicked(int )), // this, SLOT(offerTableHeaderClicked(int))); // connect(offersModel, SIGNAL(modelReset()), this, SLOT(onOffersModelReset()) ); ui_mainview.tableBrowseOffers->setCurrentIndex(offersModel->index(0, 0)); } void iotstockView::setupMeasuresModel() { if (db.isOpen()) { measuresModel->setTable("measures"); measuresModel->setEditStrategy(QSqlTableModel::OnFieldChange); measuresModel->setHeaderData(measuresModel->fieldIndex("text"), Qt::Horizontal, i18n("Description")); ui_mainview.tableMeasures->setModel(measuresModel); ui_mainview.tableMeasures->setSelectionMode(QAbstractItemView::SingleSelection); ui_mainview.tableMeasures->setColumnHidden(measuresModel->fieldIndex("id"), true); ui_mainview.tableMeasures->setItemDelegate(new QItemDelegate(ui_mainview.tableMeasures)); measuresModel->select(); ui_mainview.tableMeasures->setCurrentIndex(measuresModel->index(0, 0)); } else { //At this point, what to do? // inform to the user about the error and finish app or retry again some time later? QString details = db.lastError().text(); KMessageBox::detailedError(this, i18n("Iotstock has encountered an error, click details to see the error details."), details, i18n("Error")); QTimer::singleShot(10000, this, SLOT(setupMeasuresModel())); } } void iotstockView::setupCategoriesModel() { if (db.isOpen()) { categoriesModel->setTable("categories"); categoriesModel->setEditStrategy(QSqlTableModel::OnFieldChange); categoriesModel->setHeaderData(categoriesModel->fieldIndex("text"), Qt::Horizontal, i18n("Description")); ui_mainview.tableCategories->setModel(categoriesModel); ui_mainview.tableCategories->setSelectionMode(QAbstractItemView::SingleSelection); ui_mainview.tableCategories->setColumnHidden(categoriesModel->fieldIndex("catid"), true); //ui_mainview.tableCategories->setItemDelegate(new QItemDelegate(ui_mainview.tableCategories)); categoriesModel->select(); ui_mainview.tableCategories->setCurrentIndex(categoriesModel->index(0, 0)); // BFB: Adjust column width to content ui_mainview.tableCategories->resizeColumnsToContents(); } else { //At this point, what to do? // inform to the user about the error and finish app or retry again some time later? QString details = db.lastError().text(); KMessageBox::detailedError(this, i18n("Iotstock has encountered an error, click details to see the error details."), details, i18n("Error")); QTimer::singleShot(10000, this, SLOT(setupCategoriesModel())); } } void iotstockView::setupDepartmentsModel() { if (db.isOpen()) { departmentsModel->setTable("departments"); departmentsModel->setEditStrategy(QSqlTableModel::OnFieldChange); departmentsModel->setHeaderData(departmentsModel->fieldIndex("text"), Qt::Horizontal, i18n("Description")); ui_mainview.tableDepartments->setModel(departmentsModel); ui_mainview.tableDepartments->setSelectionMode(QAbstractItemView::SingleSelection); ui_mainview.tableDepartments->setColumnHidden(departmentsModel->fieldIndex("id"), true); //ui_mainview.tableDepartments->setItemDelegate(new QItemDelegate(ui_mainview.tableDepartments)); departmentsModel->select(); ui_mainview.tableDepartments->setCurrentIndex(departmentsModel->index(0, 0)); // BFB: Adjust column width to content ui_mainview.tableDepartments->resizeColumnsToContents(); } else { //At this point, what to do? // inform to the user about the error and finish app or retry again some time later? QString details = db.lastError().text(); KMessageBox::detailedError(this, i18n("Iotstock has encountered an error, click details to see the error details."), details, i18n("Error")); QTimer::singleShot(10000, this, SLOT(setupCategoriesModel())); } } void iotstockView::setupSubCategoriesModel() { if (db.isOpen()) { subcategoriesModel->setTable("subcategories"); subcategoriesModel->setEditStrategy(QSqlTableModel::OnFieldChange); subcategoriesModel->setHeaderData(subcategoriesModel->fieldIndex("text"), Qt::Horizontal, i18n("Description")); ui_mainview.tableSubCategories->setModel(subcategoriesModel); ui_mainview.tableSubCategories->setSelectionMode(QAbstractItemView::SingleSelection); ui_mainview.tableSubCategories->setColumnHidden(subcategoriesModel->fieldIndex("id"), true); //ui_mainview.tableSubCategories->setColumnHidden(subcategoriesModel->fieldIndex("parent"), true); ui_mainview.tableSubCategories->setItemDelegate(new QItemDelegate(ui_mainview.tableSubCategories)); subcategoriesModel->setRelation(subcategoriesModel->fieldIndex("parent"), QSqlRelation("categories", "catid", "text")); subcategoriesModel->setHeaderData(subcategoriesModel->fieldIndex("parent"), Qt::Horizontal, i18n("Parent Category")); //NOTE: The problem with relations is that parent must point to an existent category, 0/NULL makes to show NOTHING in the table. ui_mainview.tableSubCategories->setItemDelegate(new QSqlRelationalDelegate(ui_mainview.tableSubCategories)); subcategoriesModel->select(); ui_mainview.tableSubCategories->setCurrentIndex(subcategoriesModel->index(0, 0)); ui_mainview.tableSubCategories->resizeColumnsToContents(); } else { //At this point, what to do? // inform to the user about the error and finish app or retry again some time later? QString details = db.lastError().text(); KMessageBox::detailedError(this, i18n("Iotstock has encountered an error, click details to see the error details."), details, i18n("Error")); QTimer::singleShot(10000, this, SLOT(setupSubCategoriesModel())); } } void iotstockView::setupClientsModel() { if (db.isOpen()) { clientsModel->setTable("clients"); ui_mainview.clientsView->setViewMode(QListView::IconMode); ui_mainview.clientsView->setGridSize(QSize(170,170)); ui_mainview.clientsView->setEditTriggers(QAbstractItemView::NoEditTriggers); ui_mainview.clientsView->setResizeMode(QListView::Adjust); ui_mainview.clientsView->setModel(clientsModel); ui_mainview.clientsView->setModelColumn(clientsModel->fieldIndex("photo")); ui_mainview.clientsView->setSelectionMode(QAbstractItemView::SingleSelection); UsersDelegate *delegate = new UsersDelegate(ui_mainview.clientsView); ui_mainview.clientsView->setItemDelegate(delegate); clientsModel->select(); ui_mainview.clientsView->setCurrentIndex(clientsModel->index(0, 0)); } else { //At this point, what to do? // inform to the user about the error and finish app or retry again some time later? QString details = db.lastError().text(); KMessageBox::detailedError(this, i18n("Iotstock has encountered an error, click details to see the error details."), details, i18n("Error")); QTimer::singleShot(10000, this, SLOT(setupClientsModel())); } } void iotstockView::setupTransactionsModel() { openDB(); qDebug()<<"setupTransactions.."; if (db.isOpen()) { transactionsModel->setTable("transactions"); transIdIndex = transactionsModel->fieldIndex("id"); transClientidIndex = transactionsModel->fieldIndex("clientid"); transTypeIndex= transactionsModel->fieldIndex("type"); transAmountIndex= transactionsModel->fieldIndex("amount"); transDateIndex = transactionsModel->fieldIndex("date"); transTimeIndex= transactionsModel->fieldIndex("time"); transPaidWithIndex= transactionsModel->fieldIndex("paidwith"); transChangeGivenIndex= transactionsModel->fieldIndex("changegiven"); transPayMethodIndex = transactionsModel->fieldIndex("paymethod"); transStateIndex= transactionsModel->fieldIndex("state"); transUseridIndex=transactionsModel->fieldIndex("userid"); transCardNumIndex=transactionsModel->fieldIndex("cardnumber"); transItemCountIndex=transactionsModel->fieldIndex("itemcount"); transItemsListIndex=transactionsModel->fieldIndex("itemslist"); transPointsIndex=transactionsModel->fieldIndex("points"); transDiscMoneyIndex=transactionsModel->fieldIndex("discmoney"); transDiscIndex=transactionsModel->fieldIndex("disc"); transCardAuthNumberIndex=transactionsModel->fieldIndex("cardauthnumber"); transUtilityIndex=transactionsModel->fieldIndex("utility"); transTerminalNumIndex=transactionsModel->fieldIndex("terminalnum"); transProvIdIndex = transactionsModel->fieldIndex("providerid"); transSOIndex = transactionsModel->fieldIndex("specialOrders"); int transCardTypeId = transactionsModel->fieldIndex("cardtype"); ui_mainview.transactionsTable->setModel(transactionsModel); ui_mainview.transactionsTable->setEditTriggers(QAbstractItemView::NoEditTriggers); ui_mainview.transactionsTable->setColumnHidden(transItemsListIndex, true); ui_mainview.transactionsTable->setColumnHidden(transSOIndex, true); transactionsModel->setRelation(transTypeIndex, QSqlRelation("transactiontypes", "ttypeid", "text")); transactionsModel->setRelation(transStateIndex, QSqlRelation("transactionstates", "stateid", "text")); transactionsModel->setRelation(transPayMethodIndex, QSqlRelation("paytypes", "typeid", "text")); transactionsModel->setRelation(transClientidIndex, QSqlRelation("clients", "id", "name")); transactionsModel->setRelation(transUseridIndex, QSqlRelation("users", "id", "username")); transactionsModel->setRelation(transProvIdIndex, QSqlRelation("providers", "id", "name")); transactionsModel->setRelation(transCardTypeId, QSqlRelation("cardtypes", "typeid", "text")); transactionsModel->setHeaderData(transIdIndex, Qt::Horizontal, i18n("Id")); transactionsModel->setHeaderData(transClientidIndex, Qt::Horizontal, i18n("Client")); transactionsModel->setHeaderData(transTypeIndex, Qt::Horizontal, i18n("Type") ); transactionsModel->setHeaderData(transAmountIndex, Qt::Horizontal, i18n("Amount") ); transactionsModel->setHeaderData(transDateIndex, Qt::Horizontal, i18n("Date") ); transactionsModel->setHeaderData(transTimeIndex, Qt::Horizontal, i18n("Time") ); transactionsModel->setHeaderData(transPaidWithIndex, Qt::Horizontal, i18n("Paid with") ); transactionsModel->setHeaderData(transChangeGivenIndex, Qt::Horizontal, i18n("Change Given") ); transactionsModel->setHeaderData(transPayMethodIndex, Qt::Horizontal, i18n("Pay Method") ); transactionsModel->setHeaderData(transStateIndex, Qt::Horizontal, i18n("State") ); transactionsModel->setHeaderData(transUseridIndex, Qt::Horizontal, i18n("Vendor") ); transactionsModel->setHeaderData(transCardNumIndex, Qt::Horizontal, i18n("Card Num") ); transactionsModel->setHeaderData(transItemCountIndex, Qt::Horizontal, i18n("Items Count") ); transactionsModel->setHeaderData(transPointsIndex, Qt::Horizontal, i18n("Points") ); transactionsModel->setHeaderData(transDiscMoneyIndex, Qt::Horizontal, i18n("Discount %1", KGlobal::locale()->currencySymbol()) ); transactionsModel->setHeaderData(transDiscIndex, Qt::Horizontal, i18n("Discount %") ); transactionsModel->setHeaderData(transCardAuthNumberIndex, Qt::Horizontal, i18n("Card Authorization #") ); transactionsModel->setHeaderData(transUtilityIndex, Qt::Horizontal, i18n("Profit") ); transactionsModel->setHeaderData(transTerminalNumIndex, Qt::Horizontal, i18n("Terminal #") ); transactionsModel->setHeaderData(transProvIdIndex, Qt::Horizontal, i18n("Provider") ); transactionsModel->setHeaderData(transCardTypeId, Qt::Horizontal, i18n("Card Type") ); ui_mainview.transactionsTable->setColumnHidden(transactionsModel->fieldIndex("totalTax"), true); ui_mainview.transactionsTable->setColumnHidden(transactionsModel->fieldIndex("specialOrders"), true); ui_mainview.transactionsTable->setColumnHidden(transactionsModel->fieldIndex("itemlist"), true); //ui_mainview.transactionsTable->setColumnHidden(transactionsModel->fieldIndex("disc"), true); ui_mainview.transactionsTable->setSelectionMode(QAbstractItemView::SingleSelection); transactionsModel->select(); updateCardTypesCombo(); } qDebug()<<"setupTransactions.. done, "<<transactionsModel->lastError(); } //FIXME: When filtering by User/Client, we need filter by user or username? and just = or with a regexp or a 'like' search?? void iotstockView::setTransactionsFilter() { //NOTE: This is a QT BUG. // If filter by description is selected and the text is empty, and later is re-filtered // then NO pictures are shown; even if is refiltered again. QRegExp regexp; Azahar *myDb = new Azahar; myDb->setDatabase(db); if (!ui_mainview.groupFilterTransactions->isChecked()) transactionsModel->setFilter(""); else { if (ui_mainview.rbTransFilterByUser->isChecked()) { //1st if: Filter by Users. regexp = QRegExp(ui_mainview.editTransUsersFilter->text()); if (!regexp.isValid() || ui_mainview.editTransUsersFilter->text().isEmpty()) ui_mainview.editTransUsersFilter->setText("*"); if (ui_mainview.editTransUsersFilter->text()=="*") transactionsModel->setFilter(""); else { unsigned int uid = myDb->getUserId(ui_mainview.editTransUsersFilter->text()); transactionsModel->setFilter(QString("transactions.userid=%1").arg(uid)); } transactionsModel->setSort(transIdIndex, Qt::DescendingOrder); } else if (ui_mainview.rbTransFilterByClient->isChecked()) { //2nd if: Filter by CLIENTS regexp = QRegExp(ui_mainview.editTransClientsFilter->text()); if (!regexp.isValid() || ui_mainview.editTransClientsFilter->text().isEmpty()) ui_mainview.editTransClientsFilter->setText(""); if (ui_mainview.editTransClientsFilter->text()=="") transactionsModel->setFilter(""); else { unsigned int cid = myDb->getClientId(ui_mainview.editTransClientsFilter->text()); transactionsModel->setFilter(QString("transactions.clientid=%1").arg(cid)); } transactionsModel->setSort(transIdIndex, Qt::DescendingOrder); } else if (ui_mainview.rbTransFilterByStateFinished->isChecked()) { //3rd if: filter by FINISHED TRANSACTIONS transactionsModel->setFilter(QString("transactions.state=2")); //tCompleted=2 transactionsModel->setSort(transIdIndex, Qt::DescendingOrder); } else if (ui_mainview.rbTransFilterByStateCancelled->isChecked()) { //4th if: filter by CANCELLED TRANSACTIONS transactionsModel->setFilter(QString("transactions.state=3")); //tCancelled=3 transactionsModel->setSort(transIdIndex, Qt::DescendingOrder); } else if (ui_mainview.rbTransFilterByPaidCash->isChecked()) { //5th if: filter by PAID IN CASH transactionsModel->setFilter("transactions.paymethod=1 and transactions.state=2"); // paid in cash and finished transactionsModel->setSort(transIdIndex, Qt::DescendingOrder); } else if (ui_mainview.rbTransFilterByPaidCredit->isChecked()) { //6th if: filter by PAID WITH CARD QString cardTypeStr = ui_mainview.comboCardTypes->currentText(); int cardTypeId = cardTypesHash.value(cardTypeStr); transactionsModel->setFilter(QString("transactions.paymethod=2 and transactions.state=2 and transactions.cardtype=%1").arg(cardTypeId)); //paid with card and finished only transactionsModel->setSort(transIdIndex, Qt::AscendingOrder); } else if (ui_mainview.rbTransFilterByDate->isChecked()) { //7th if: filter by DATE QDate date = ui_mainview.transactionsDateEditor->date(); transactionsModel->setFilter(QString("transactions.date = '%1'").arg(date.toString("yyyy-MM-dd"))); qDebug()<<"Filtro:"<<transactionsModel->filter(); transactionsModel->setSort(transIdIndex, Qt::DescendingOrder); } else if (ui_mainview.rbTransFilterByAmountLess->isChecked()) { //6th if: filter by AMOUNT < double amo = ui_mainview.editTransAmountLess->value(); transactionsModel->setFilter(QString("transactions.amount<%1").arg(amo)); transactionsModel->setSort(transIdIndex, Qt::AscendingOrder); } else if (ui_mainview.rbTransFilterByAmountGreater->isChecked()) { //6th if: filter by AMOUNT > double amo = ui_mainview.editTransAmountGreater->value(); transactionsModel->setFilter(QString("transactions.amount>%1").arg(amo)); transactionsModel->setSort(transIdIndex, Qt::AscendingOrder); } //NOTE: in the next 3 ifs, transactions.type=X is hardcoded... I assume the user did not change the default values. else if (ui_mainview.rbTransactionsFilterOnlySales->isChecked()) { transactionsModel->setFilter("transactions.type=1"); transactionsModel->setSort(transIdIndex, Qt::DescendingOrder); } else if (ui_mainview.rbTransactionsFilterOnlyPurchases->isChecked()) { transactionsModel->setFilter("transactions.type=2"); transactionsModel->setSort(transIdIndex, Qt::DescendingOrder); } else if (ui_mainview.rbTransactionsFilterOnlyChangesReturns->isChecked()) { transactionsModel->setFilter("transactions.type=3 OR transactions.type=4"); transactionsModel->setSort(transIdIndex, Qt::DescendingOrder); } else { //else: filter by terminal number unsigned int tnum = ui_mainview.editTransTermNum->value(); transactionsModel->setFilter(QString("transactions.terminalnum=%1").arg(tnum)); transactionsModel->setSort(transIdIndex, Qt::AscendingOrder); } transactionsModel->select(); } delete myDb; } //CURRENCIES void iotstockView::setupCurrenciesModel() { if (db.isOpen()) { currenciesModel->setTable("currencies"); currenciesModel->setEditStrategy(QSqlTableModel::OnFieldChange); currenciesModel->setHeaderData(currenciesModel->fieldIndex("name"), Qt::Horizontal, i18n("Name")); ui_mainview.tableCurrencies->setModel(currenciesModel); ui_mainview.tableCurrencies->setSelectionMode(QAbstractItemView::SingleSelection); ui_mainview.tableCurrencies->setColumnHidden(currenciesModel->fieldIndex("id"), true); ui_mainview.tableCurrencies->setItemDelegate(new QItemDelegate(ui_mainview.tableCurrencies)); currenciesModel->select(); ui_mainview.tableCurrencies->setCurrentIndex(currenciesModel->index(0, 0)); } else { //At this point, what to do? // inform to the user about the error and finish app or retry again some time later? QString details = db.lastError().text(); KMessageBox::detailedError(this, i18n("Iotstock has encountered an error, click details to see the error details."), details, i18n("Error")); QTimer::singleShot(10000, this, SLOT(setupCurrenciesModel())); } } // BALANCES void iotstockView::setupBalancesModel() { openDB(); qDebug()<<"setupBalances.. after openDB"; if (db.isOpen()) { balancesModel->setTable("balances"); balanceIdIndex = balancesModel->fieldIndex("id"); balanceDateEndIndex = balancesModel->fieldIndex("datetime_end"); //just one date... balanceUserNameIndex= balancesModel->fieldIndex("usern"); balanceInitAmountIndex= balancesModel->fieldIndex("initamount"); balanceInIndex = balancesModel->fieldIndex("in"); balanceOutIndex= balancesModel->fieldIndex("out"); balanceCashIndex= balancesModel->fieldIndex("cash"); balanceCardIndex= balancesModel->fieldIndex("card"); balanceTransIndex = balancesModel->fieldIndex("transactions"); balanceTerminalNumIndex= balancesModel->fieldIndex("terminalnum"); balanceDateStartIndex=balancesModel->fieldIndex("datetime_start"); //to hide balanceUseridIndex=balancesModel->fieldIndex("userid"); //to hide ui_mainview.balancesTable->setModel(balancesModel); ui_mainview.balancesTable->setEditTriggers(QAbstractItemView::NoEditTriggers); ui_mainview.balancesTable->setColumnHidden(balanceDateStartIndex, true); ui_mainview.balancesTable->setColumnHidden(balanceUseridIndex, true); balancesModel->setHeaderData(balanceIdIndex, Qt::Horizontal, i18n("Id")); balancesModel->setHeaderData(balanceDateEndIndex, Qt::Horizontal, i18n("Date")); balancesModel->setHeaderData(balanceUserNameIndex, Qt::Horizontal, i18n("Vendor") ); balancesModel->setHeaderData(balanceInitAmountIndex, Qt::Horizontal, i18n("Initial amount") ); balancesModel->setHeaderData(balanceInIndex, Qt::Horizontal, i18n("In") ); balancesModel->setHeaderData(balanceOutIndex, Qt::Horizontal, i18n("Out") ); balancesModel->setHeaderData(balanceCashIndex, Qt::Horizontal, i18n("Cash in drawer") ); balancesModel->setHeaderData(balanceCardIndex, Qt::Horizontal, i18n("Received by Card") ); balancesModel->setHeaderData(balanceTransIndex, Qt::Horizontal, i18n("Transactions") ); balancesModel->setHeaderData(balanceTerminalNumIndex, Qt::Horizontal, i18n("Terminal #") ); ui_mainview.balancesTable->setSelectionMode(QAbstractItemView::SingleSelection); // ProductDelegate *delegate = new ProductDelegate(ui_mainview.productsView); // ui_mainview.productsView->setItemDelegate(delegate); balancesModel->select(); } qDebug()<<"setupBalances.. done."; } //FIXME: When filtering by User, we need filter by user or username? and just = or with a regexp or a 'like' search?? void iotstockView::setBalancesFilter() { //NOTE: This is a QT BUG. // If filter by description is selected and the text is empty, and later is re-filtered // then NO pictures are shown; even if is refiltered again. if (!ui_mainview.groupFilterBalances->isChecked()) balancesModel->setFilter(""); else { if (ui_mainview.rbBalancesFilterByState->isChecked()) { //1st if: Filter by NOT EMPTY Transactions on balances balancesModel->setFilter(QString("balances.transactions!='EMPTY'")); balancesModel->setSort(balanceIdIndex, Qt::DescendingOrder); } else if (ui_mainview.rbBalancesFilterBySuspicious->isChecked()) { //2nd if: Filter by Suspicious balances balancesModel->setFilter(QString("balances.initamount+balances.in-balances.out!=balances.cash")); balancesModel->setSort(balanceIdIndex, Qt::DescendingOrder); } else if (ui_mainview.rbBalancesFilterByDate->isChecked()) { //3rd if: filter by DATE QDate date = ui_mainview.editBalancesFilterByDate->date(); QDateTime dt = QDateTime(date); //time 00:00:00 QString dtStr = dt.toString("yyyy-MM-dd hh:mm:ss"); QString dtStr2= date.toString("yyyy-MM-dd")+" 23:59:59"; balancesModel->setFilter(QString("balances.datetime_end>='%1' and balances.datetime_end<='%2'").arg(dtStr).arg(dtStr2)); qDebug()<<"Filtro:"<<balancesModel->filter(); balancesModel->setSort(balanceIdIndex, Qt::DescendingOrder); } else if (ui_mainview.rbBalancesFilterByCashInLess->isChecked()) { //4th if: filter by CASH IN < double amo = ui_mainview.editBalancesFilterByCasInLess->value(); balancesModel->setFilter(QString("balances.in<%1").arg(amo)); balancesModel->setSort(balanceIdIndex, Qt::DescendingOrder); } else if (ui_mainview.rbBalancesFilterByCashInGrater->isChecked()) { //5th if: filter by CASH IN > double csh = ui_mainview.editBalancesFilterByCashInGrater->value(); balancesModel->setFilter(QString("balances.in>%1").arg(csh)); balancesModel->setSort(balanceIdIndex, Qt::DescendingOrder); } else if (ui_mainview.rbBalancesFilterByUser->isChecked()) { //6th if: filter by vendor balancesModel->setFilter(QString("balances.usern='%1'").arg(ui_mainview.editBalancesFilterByVendor->text())); balancesModel->setSort(balanceIdIndex, Qt::DescendingOrder); } else { //7th else: filter by terminal number unsigned int tnum = ui_mainview.editBalancesFilterByTermNum->value(); balancesModel->setFilter(QString("balances.terminalnum=%1").arg(tnum)); balancesModel->setSort(balanceIdIndex, Qt::DescendingOrder); } balancesModel->select(); } } // Special Orders void iotstockView::setupSpecialOrdersModel() { openDB(); qDebug()<<"setup special orders.. after openDB"; if (db.isOpen()) { specialOrdersModel->setTable("special_orders"); ///NOTE: Here we can use the v_groupedSO table instead, to group them by saleid /// I dont know how convenient is this. int soIdIndex = specialOrdersModel->fieldIndex("orderid"); int soDateIndex = specialOrdersModel->fieldIndex("dateTime"); int soNameIndex= specialOrdersModel->fieldIndex("name"); int soGroupElemIndex= specialOrdersModel->fieldIndex("groupElements"); int soQtyIndex = specialOrdersModel->fieldIndex("qty"); int soPriceIndex= specialOrdersModel->fieldIndex("price"); int soCostIndex= specialOrdersModel->fieldIndex("cost"); int soUnitsIndex= specialOrdersModel->fieldIndex("units"); int soStatusIndex = specialOrdersModel->fieldIndex("status"); int soSaleIdIndex= specialOrdersModel->fieldIndex("saleid"); int soNotesIndex=specialOrdersModel->fieldIndex("notes"); int soPaymentIndex=specialOrdersModel->fieldIndex("payment"); int soCompletePaymentIndex=specialOrdersModel->fieldIndex("completePayment"); ui_mainview.tableSO->setModel(specialOrdersModel); ui_mainview.tableSO->setEditTriggers(QAbstractItemView::NoEditTriggers); ui_mainview.tableSO->setColumnHidden(soGroupElemIndex, true); ui_mainview.tableSO->setColumnHidden(soUnitsIndex, true); specialOrdersModel->setHeaderData(soIdIndex, Qt::Horizontal, i18n("Order #")); specialOrdersModel->setHeaderData(soNameIndex, Qt::Horizontal, i18n("Name")); specialOrdersModel->setHeaderData(soDateIndex, Qt::Horizontal, i18n("Date") ); specialOrdersModel->setHeaderData(soQtyIndex, Qt::Horizontal, i18n("Qty") ); specialOrdersModel->setHeaderData(soPriceIndex, Qt::Horizontal, i18n("Price") ); specialOrdersModel->setHeaderData(soCostIndex, Qt::Horizontal, i18n("Cost") ); specialOrdersModel->setHeaderData(soUnitsIndex, Qt::Horizontal, i18n("Sold by") ); specialOrdersModel->setHeaderData(soStatusIndex, Qt::Horizontal, i18n("Status") ); specialOrdersModel->setHeaderData(soSaleIdIndex, Qt::Horizontal, i18n("Tr. Id") ); specialOrdersModel->setHeaderData(soNotesIndex, Qt::Horizontal, i18n("Notes") ); specialOrdersModel->setHeaderData(soPaymentIndex, Qt::Horizontal, i18n("Payment") ); specialOrdersModel->setHeaderData(soCompletePaymentIndex, Qt::Horizontal, i18n("Payment Complete") ); //relations specialOrdersModel->setRelation(soUnitsIndex, QSqlRelation("measures", "id", "text")); specialOrdersModel->setRelation(soStatusIndex, QSqlRelation("so_status", "id", "text")); specialOrdersModel->setRelation(soCompletePaymentIndex, QSqlRelation("bool_values", "id", "text")); ui_mainview.tableSO->setSelectionMode(QAbstractItemView::SingleSelection); specialOrdersModel->select(); } qDebug()<<"setup special orders.. done."; } void iotstockView::setSpecialOrdersFilter() { if (!ui_mainview.groupSOFilter->isChecked()) specialOrdersModel->setFilter(""); else { if (ui_mainview.rbSOByDate->isChecked()) { //1st if: Filter by date QDate d = ui_mainview.datePicker->date(); QDateTime dt = QDateTime(d); QString dtStr = dt.toString("yyyy-MM-dd hh:mm:ss"); QString dtStr2= d.toString("yyyy-MM-dd")+" 23:59:59"; specialOrdersModel->setFilter(QString("special_orders.dateTime>='%1' and special_orders.dateTime<='%2'").arg(dtStr).arg(dtStr2)); specialOrdersModel->setSort(12, Qt::DescendingOrder); //by date } else if (ui_mainview.rbSOByThisWeek->isChecked()) { //2nd if: Filter by one week specialOrdersModel->setFilter(QString("special_orders.dateTime > ADDDATE(sysdate( ), INTERVAL -8 DAY )")); specialOrdersModel->setSort(0, Qt::DescendingOrder); //orderid } else if (ui_mainview.rbSOByThisMonth->isChecked()) { //3rd if: filter by ONE Month specialOrdersModel->setFilter(QString("special_orders.dateTime > ADDDATE(sysdate( ), INTERVAL -31 DAY )")); specialOrdersModel->setSort(0, Qt::DescendingOrder); //orderid } else if (ui_mainview.rbSOByStatusPending->isChecked()) { //4th if: filter by STATUS PENDING specialOrdersModel->setFilter(QString("special_orders.status=0")); specialOrdersModel->setSort(0, Qt::DescendingOrder); } else if (ui_mainview.rbSOByStatusInProgress->isChecked()) { //4th if: filter by STATUS IN PROGRESS specialOrdersModel->setFilter(QString("special_orders.status=1")); specialOrdersModel->setSort(0, Qt::DescendingOrder); } else if (ui_mainview.rbSOByStatusReady->isChecked()) { //4th if: filter by STATUS READY specialOrdersModel->setFilter(QString("special_orders.status=2")); specialOrdersModel->setSort(0, Qt::DescendingOrder); } else if (ui_mainview.rbSOByStatusDelivered->isChecked()) { //4th if: filter by STATUS DELIVERED specialOrdersModel->setFilter(QString("special_orders.status=3")); specialOrdersModel->setSort(0, Qt::DescendingOrder); } else { //4th if: filter by STATUS CANCELLED specialOrdersModel->setFilter(QString("special_orders.status=4")); specialOrdersModel->setSort(0, Qt::DescendingOrder); } specialOrdersModel->select(); } } //reservationsModel void iotstockView::setupReservationsModel() { if (db.isOpen()) { reservationsModel->setTable("reservations"); reservationsModel->setEditStrategy(QSqlTableModel::OnFieldChange); reservationsModel->setHeaderData(reservationsModel->fieldIndex("id"), Qt::Horizontal, i18n("Reservation")); reservationsModel->setHeaderData(reservationsModel->fieldIndex("transaction_id"), Qt::Horizontal, i18n("Tr. #")); reservationsModel->setHeaderData(reservationsModel->fieldIndex("client_id"), Qt::Horizontal, i18n("Client")); reservationsModel->setHeaderData(reservationsModel->fieldIndex("date"), Qt::Horizontal, i18n("Date")); reservationsModel->setHeaderData(reservationsModel->fieldIndex("status"), Qt::Horizontal, i18n("Status")); reservationsModel->setHeaderData(reservationsModel->fieldIndex("payment"), Qt::Horizontal, i18n("Prepayment")); reservationsModel->setHeaderData(reservationsModel->fieldIndex("total"), Qt::Horizontal, i18n("Total")); reservationsModel->setRelation(reservationsModel->fieldIndex("client_id"), QSqlRelation("clients", "id", "name")); reservationsModel->setRelation(reservationsModel->fieldIndex("status_id"), QSqlRelation("transactionstates", "stateid", "text")); ui_mainview.tableReservations->setModel(reservationsModel); ui_mainview.tableReservations->setSelectionMode(QAbstractItemView::SingleSelection); ui_mainview.tableReservations->setColumnHidden(reservationsModel->fieldIndex("totaltaxes"), true); ui_mainview.tableReservations->setItemDelegate(new QItemDelegate(ui_mainview.tableReservations)); reservationsModel->select(); ui_mainview.tableReservations->setCurrentIndex(reservationsModel->index(0, 0)); } else { //At this point, what to do? // inform to the user about the error and finish app or retry again some time later? QString details = db.lastError().text(); KMessageBox::detailedError(this, i18n("Iotstock has encountered an error, click details to see the error details."), details, i18n("Error")); QTimer::singleShot(10000, this, SLOT(setupReservationsModel())); } } void iotstockView::reservationsOnSelected(const QModelIndex &index) { if (db.isOpen()) { //getting data from model... const QAbstractItemModel *model = index.model(); int row = index.row(); QModelIndex indx = model->index(row, reservationsModel->fieldIndex("id")); qulonglong id = model->data(indx, Qt::DisplayRole).toULongLong(); ReservationInfo rInfo; QList<TransactionItemInfo> rItems; Azahar *myDb = new Azahar; myDb->setDatabase(db); rInfo = myDb->getReservationInfo(id); rItems = myDb->getTransactionItems(rInfo.transaction_id); delete myDb; //Draw the reservation details QString text = QString("<b><span style=\" font-size:13pt;\">%1 <br>%2 </span></b><br><br><i>%3</i><br><ul>") .arg(tr("Transaction No.%1").arg(rInfo.transaction_id)) .arg(tr("Reservation No.%1").arg(rInfo.id)) .arg(tr("Reserved Items:")); //get each item foreach(TransactionItemInfo item, rItems ) { text += QString("<li> %1 x %2</li>").arg(QString::number(item.qty)).arg(item.name); //TODO: display nested items if the item is a group } text += "</ul>"; ui_mainview.lblReservationDetails->setText(text); } } /* widgets */ void iotstockView::settingsChanged() { emit signalChangeStatusbar( i18n("Settings changed") ); db.setHostName(Settings::editDBServer()); db.setDatabaseName(Settings::editDBName()); db.setUserName(Settings::editDBUsername()); db.setPassword(Settings::editDBPassword()); connectToDb(); updateGraphs(); } void iotstockView::settingsChangedOnInitConfig() { qDebug()<<"==> Initial Config Changed- connecting to database and calling login..."; db.setHostName(Settings::editDBServer()); db.setDatabaseName(Settings::editDBName()); db.setUserName(Settings::editDBUsername()); db.setPassword(Settings::editDBPassword()); connectToDb(); login(); } void iotstockView::setOffersFilter() { if (ui_mainview.groupFilterOffers->isChecked()) { if (ui_mainview.chOffersFilterByProduct->isChecked()) { ui_mainview.editOffersFilterByProduct->setFocus(); //Get codes and names from offers and products QString myFilter; QStringList codes; QString desc; if (ui_mainview.editOffersFilterByProduct->text().isEmpty()) desc = "."; else desc =ui_mainview.editOffersFilterByProduct->text(); Azahar *myDb = new Azahar; myDb->setDatabase(db); myFilter = myDb->getOffersFilterWithText(desc); delete myDb; if (myFilter == "") myFilter = "offers.product_id=0"; //there should not be a product with code=0 offersModel->setFilter(myFilter); } else if (ui_mainview.chOffersTodayDiscounts->isChecked()) { //Today Offers QDate date = QDate::currentDate(); QString today = date.toString("yyyy-MM-dd"); offersModel->setFilter(QString(" offers.datestart <= '%1' and offers.dateend >='%1' ").arg(today)); //offers.datestart between '%1' and '%2' or offers.dateend between %3 and %4 qDebug()<<"Filtro:"<<offersModel->filter(); } else if (ui_mainview.chOffersSelectDate->isChecked()) { //Selected Date Offers QDate date = ui_mainview.offersDateEditor->date(); // offersModel->setFilter(QString("offers.dateend='%1'").arg()); offersModel->setFilter(QString(" offers.datestart <= '%1' and offers.dateend >='%1' ").arg(date.toString("yyyy-MM-dd"))); qDebug()<<"Filtro:"<<offersModel->filter(); } else { //old offers, non valid anymore... QDate date = QDate::currentDate(); offersModel->setFilter(QString("offers.dateend<'%1'").arg(date.toString("yyyy-MM-dd"))); qDebug()<<"Filtro: "<<offersModel->filter(); } //Faltaria las ofertas aun no validas (futuras) } else offersModel->setFilter(""); //show all offers... offersModel->select(); } void iotstockView::usersViewOnSelected(const QModelIndex & index) { if (db.isOpen()) { //getting data from model... const QAbstractItemModel *model = index.model(); int row = index.row(); QModelIndex indx = model->index(row, usersModel->fieldIndex("id")); int id = model->data(indx, Qt::DisplayRole).toInt(); indx = model->index(row, usersModel->fieldIndex("username")); QString username = model->data(indx, Qt::DisplayRole).toString(); indx = model->index(row, usersModel->fieldIndex("name")); QString name = model->data(indx, Qt::DisplayRole).toString(); indx = model->index(row, usersModel->fieldIndex("address")); QString address = model->data(indx, Qt::DisplayRole).toString(); indx = model->index(row, usersModel->fieldIndex("phone")); QString phone = model->data(indx, Qt::DisplayRole).toString(); indx = model->index(row, usersModel->fieldIndex("phone_movil")); QString cell = model->data(indx, Qt::DisplayRole).toString(); indx = model->index(row, usersModel->fieldIndex("photo")); QByteArray photoBA = model->data(indx, Qt::DisplayRole).toByteArray(); indx = model->index(row, usersModel->fieldIndex("password")); QString oldPassword = model->data(indx, Qt::DisplayRole).toString(); indx = model->index(row, usersModel->fieldIndex("salt")); QString oldSalt = model->data(indx, Qt::DisplayRole).toString(); indx = model->index(row, usersModel->fieldIndex("role")); int role = model->data(indx, Qt::DisplayRole).toInt(); QPixmap photo; photo.loadFromData(photoBA); UserInfo uInfo; //Launch Edit dialog UserEditor *userEditorDlg = new UserEditor(this); //Set data on dialog userEditorDlg->setId(id); userEditorDlg->setUserName(username); userEditorDlg->setRealName(name); userEditorDlg->setAddress(address); userEditorDlg->setPhone(phone); userEditorDlg->setCell(cell); userEditorDlg->setPhoto(photo); userEditorDlg->setUserRole(role); //dont allow to scale privilages to supervisors. userEditorDlg->disableRoles(!adminIsLogged); //dont allow to change admin's password/info to a supervisor. userEditorDlg->disallowAdminChange(!adminIsLogged); if (userEditorDlg->exec() ) { uInfo.id = id; uInfo.username = userEditorDlg->getUserName(); uInfo.name = userEditorDlg->getRealName(); uInfo.address = userEditorDlg->getAddress(); uInfo.phone = userEditorDlg->getPhone(); uInfo.cell = userEditorDlg->getCell(); photo = userEditorDlg->getPhoto(); uInfo.role = userEditorDlg->getUserRole(); uInfo.photo = Misc::pixmap2ByteArray(new QPixmap(photo)); //Password if (!userEditorDlg->getNewPassword().isEmpty()) { QByteArray saltBA = Hash::getSalt(); uInfo.salt = QString(saltBA); QString pswdTmp = uInfo.salt+userEditorDlg->getNewPassword(); QByteArray passwdBA = pswdTmp.toLocal8Bit(); uInfo.password = Hash::password2hash(passwdBA); } else { uInfo.password = oldPassword; uInfo.salt = oldSalt; } //Modify data on mysql... Azahar *myDb = new Azahar; myDb->setDatabase(db); if (!myDb->updateUser(uInfo)) qDebug()<<"ERROR | Updating user:"<<myDb->lastError(); //reload loginWindow's users dlgPassword->reloadUsers(); delete myDb; usersModel->select(); } delete userEditorDlg; } } void iotstockView::productsViewOnSelected(const QModelIndex &index) { if (db.isOpen()) { //getting data from model... const QAbstractItemModel *model = index.model(); int row = index.row(); QModelIndex indx = model->index(row, productsModel->fieldIndex("code")); qulonglong id = model->data(indx, Qt::DisplayRole).toULongLong(); indx = model->index(row, productsModel->fieldIndex("photo")); QByteArray photoBA = model->data(indx, Qt::DisplayRole).toByteArray(); QPixmap photo; photo.loadFromData(photoBA); ProductInfo pInfo; //Launch Edit dialog ProductEditor *productEditorDlg = new ProductEditor(this, false); //Set data on dialog productEditorDlg->setModel(productsModel); productEditorDlg->disableCode(); //On Edit product, code cannot be changed. productEditorDlg->setStockQtyReadOnly(true); //on edit, cannot change qty to force use stockCorrection productEditorDlg->setDb(db); productEditorDlg->setCode(id); qulonglong newcode=0; //Launch dialog, and if dialog is accepted... if (productEditorDlg->exec() ) { //get changed|unchanged values newcode = productEditorDlg->getCode(); pInfo.alphaCode= productEditorDlg->getAlphacode(); pInfo.vendorCode= productEditorDlg->getVendorcode(); pInfo.code = newcode; pInfo.desc = productEditorDlg->getDescription(); //be aware of grouped products related to stock. if (productEditorDlg->isGroup()) { pInfo.stockqty = productEditorDlg->getGRoupStockMax(); pInfo.groupElementsStr = productEditorDlg->getGroupElementsStr(); pInfo.groupPriceDrop = productEditorDlg->getGroupPriceDrop(); } else { pInfo.stockqty = productEditorDlg->getStockQty(); pInfo.groupElementsStr = ""; pInfo.groupPriceDrop = 0; } pInfo.hasUnlimitedStock = productEditorDlg->hasUnlimitedStock(); pInfo.isNotDiscountable = productEditorDlg->isNotDiscountable(); pInfo.price = productEditorDlg->getPrice(); pInfo.cost = productEditorDlg->getCost(); pInfo.units = productEditorDlg->getMeasureId(); pInfo.tax = productEditorDlg->getTax1(); pInfo.extratax = productEditorDlg->getTax2(); pInfo.department= productEditorDlg->getDepartmentId(); pInfo.category = productEditorDlg->getCategoryId(); pInfo.subcategory = productEditorDlg->getSubCategoryId(); pInfo.points = productEditorDlg->getPoints(); photo = productEditorDlg->getPhoto(); pInfo.photo = Misc::pixmap2ByteArray(new QPixmap(photo)); //Photo ByteArray //FIXME: NEXT line is temporal remove on 0.8 version pInfo.lastProviderId = 1; //Next lines are for groups pInfo.isAGroup = productEditorDlg->isGroup(); pInfo.isARawProduct = productEditorDlg->isRaw(); //Update database Azahar *myDb = new Azahar; myDb->setDatabase(db); if (!myDb->updateProduct(pInfo, id)) qDebug()<<myDb->lastError(); // Checar ofertas y cambiarlas/borrarlas if (id != newcode) { if (!myDb->moveOffer(id, newcode)) qDebug()<<myDb->lastError(); } //now change stock if so --7/Sept/09 if (productEditorDlg->isCorrectingStock()) { qDebug()<<"Correcting stock. Old:"<<productEditorDlg->getOldStock()<<" New:"<<productEditorDlg->getStockQty()<<" Reason"<<productEditorDlg->getReason(); correctStock(pInfo.code, productEditorDlg->getOldStock(), productEditorDlg->getStockQty(), productEditorDlg->getReason()); } //FIXME: We must see error types, which ones are for duplicate KEYS (codes) to advertise the user. productsModel->select(); delete myDb; } delete productEditorDlg; setProductsFilter(); } } void iotstockView::clientsViewOnSelected(const QModelIndex & index) { if (db.isOpen()) { //getting data from model... const QAbstractItemModel *model = index.model(); int row = index.row(); QModelIndex indx = model->index(row, clientsModel->fieldIndex("id")); int id = model->data(indx, Qt::DisplayRole).toInt(); indx = model->index(row, clientsModel->fieldIndex("name")); QString name = model->data(indx, Qt::DisplayRole).toString(); indx = model->index(row, clientsModel->fieldIndex("code")); QString code = model->data(indx, Qt::DisplayRole).toString(); indx = model->index(row, clientsModel->fieldIndex("address")); QString address = model->data(indx, Qt::DisplayRole).toString(); indx = model->index(row, clientsModel->fieldIndex("phone")); QString phone = model->data(indx, Qt::DisplayRole).toString(); indx = model->index(row, clientsModel->fieldIndex("phone_movil")); QString cell = model->data(indx, Qt::DisplayRole).toString(); indx = model->index(row, clientsModel->fieldIndex("points")); qulonglong points = model->data(indx, Qt::DisplayRole).toULongLong(); indx = model->index(row, clientsModel->fieldIndex("discount")); double discount = model->data(indx, Qt::DisplayRole).toDouble(); indx = model->index(row, clientsModel->fieldIndex("photo")); QByteArray photoBA = model->data(indx, Qt::DisplayRole).toByteArray(); indx = model->index(row, clientsModel->fieldIndex("since")); QDate sinceDate = model->data(indx, Qt::DisplayRole).toDate(); ClientInfo cInfo; QPixmap photo; photo.loadFromData(photoBA); //Launch Edit dialog ClientEditor *clientEditorDlg = new ClientEditor(this); //Set data on dialog clientEditorDlg->setCode(code); clientEditorDlg->setId(id); clientEditorDlg->setName(name); clientEditorDlg->setAddress(address); clientEditorDlg->setPhone(phone); clientEditorDlg->setCell(cell); clientEditorDlg->setPhoto(photo); clientEditorDlg->setPoints(points); clientEditorDlg->setDiscount(discount); clientEditorDlg->setSinceDate(sinceDate); if (clientEditorDlg->exec() ) { cInfo.id = id; cInfo.code = clientEditorDlg->getCode(); cInfo.name = clientEditorDlg->getName(); cInfo.address = clientEditorDlg->getAddress(); cInfo.phone = clientEditorDlg->getPhone(); cInfo.cell = clientEditorDlg->getCell(); photo = clientEditorDlg->getPhoto(); cInfo.points = clientEditorDlg->getPoints(); cInfo.discount = clientEditorDlg->getDiscount(); cInfo.since = clientEditorDlg->getSinceDate(); cInfo.photo = Misc::pixmap2ByteArray(new QPixmap(photo)); //Modify data on mysql... if (!db.isOpen()) openDB(); Azahar *myDb = new Azahar; myDb->setDatabase(db); myDb->updateClient(cInfo); delete myDb; clientsModel->select(); } delete clientEditorDlg; } } void iotstockView::doPurchase() { //NOTE: Unlimited stock items cannot be purchased. This limitation is in the purchase editor, so here we do not need to do anything. if (db.isOpen()) { QStringList items; items.clear(); //temporal items list items.append("empty list"); //just a tweak for creating the transaction, celaning after creating it. Azahar *myDb = new Azahar; myDb->setDatabase(db); qDebug()<<"doPurchase..."; PurchaseEditor *purchaseEditorDlg = new PurchaseEditor(this); purchaseEditorDlg->setDb(db); if (purchaseEditorDlg->exec()) { //Now add a transaction for buy QDate date = QDate::currentDate(); QTime time = QTime::currentTime(); TransactionInfo tInfo; tInfo.type = tBuy; tInfo.amount = purchaseEditorDlg->getTotalBuy(); tInfo.date = date; tInfo.time = time; tInfo.paywith = 0.0; tInfo.changegiven = 0.0; tInfo.paymethod = pCash; tInfo.state = tCompleted; tInfo.userid = 1; tInfo.clientid= 1; tInfo.cardnumber = "-NA-"; tInfo.cardauthnum = "-NA-"; tInfo.itemcount = purchaseEditorDlg->getItemCount(); tInfo.itemlist = items.join(";"); tInfo.utility = 0; //FIXME: utility is calculated until products are sold, not before. tInfo.terminalnum = 0; //NOTE: Not really a terminal... from admin computer. tInfo.providerid = 1; //FIXME! //tInfo.groups = ""; //DEPRECATED tInfo.specialOrders = ""; tInfo.balanceId = 0; tInfo.totalTax = purchaseEditorDlg->getTotalTaxes(); qulonglong trnum = myDb->insertTransaction(tInfo); //to get the transaction number to insert in the log. if ( trnum <= 0 ) { qDebug()<<"ERROR: Could not create a Purchase Transaction ::doPurchase()"; qDebug()<<"Error:"<<myDb->lastError(); //TODO: Notify the user about the error. } //Now cleaning the items to fill with real items... items.clear(); //assigning new transaction id to the tInfo. tInfo.id = trnum; QHash<qulonglong, ProductInfo> hash = purchaseEditorDlg->getHash(); ProductInfo info; //Iterate the hash QHashIterator<qulonglong, ProductInfo> i(hash); while (i.hasNext()) { i.next(); info = i.value(); double oldstockqty = info.stockqty; info.stockqty = info.purchaseQty+oldstockqty; //Modify data on mysql... //validDiscount is for checking if product already exists on db. see line # 396 of purchaseeditor.cpp if (info.validDiscount) { if (!myDb->updateProduct(info, info.code)) qDebug()<<myDb->lastError(); else { log(loggedUserId, QDate::currentDate(), QTime::currentTime(), i18n("Purchase #%4 - %1 x %2 (%3)", info.purchaseQty, info.desc, info.code, trnum) ); qDebug()<<"Product updated [purchase] ok..."; } } else { if (!myDb->insertProduct(info)) qDebug()<<myDb->lastError(); else { log(loggedUserId, QDate::currentDate(), QTime::currentTime(), i18n("Purchase #%4 - [new] - %1 x %2 (%3)", info.purchaseQty, info.desc, info.code, trnum) ); } } productsModel->select(); items.append(QString::number(info.code)+"/"+QString::number(info.purchaseQty)); } //update items in transaction data tInfo.itemlist = items.join(";"); myDb->updateTransaction(tInfo); } delete myDb; } } void iotstockView::stockCorrection() { //launch a dialong asking: Item code, New stockQty, and reason. double newStockQty =0; double oldStockQty = 0; qulonglong pcode=0; QString reason; bool ok = false; InputDialog *dlg = new InputDialog(this, false, dialogStockCorrection, i18n("Enter the quantity and reason for the change, then press <ENTER> to accept, <ESC> to cancel")); if (dlg->exec()) { newStockQty = dlg->dValue; reason = dlg->reason; pcode = dlg->getPCode(); ok = true; } if (ok) { //send data to database... Azahar *myDb = new Azahar; myDb->setDatabase(db); oldStockQty = myDb->getProductStockQty(pcode); ProductInfo p = myDb->getProductInfo(QString::number(pcode)); bool isAGroup = p.isAGroup; //if is an Unlimited stock product, do not allow to make the correction. if (p.hasUnlimitedStock) { notifierPanel->setSize(350,150); notifierPanel->setOnBottom(false); notifierPanel->showNotification("<b>Unlimited Stock Products cannot be purchased.</b>",5000); qDebug()<<"Unlimited Stock Products cannot be purchased."; return; } if (isAGroup) { //Notify to the user that this product's stock cannot be modified. //This is because if we modify each content's stock, all items will be at the same stock level, and it may not be desired. //We can even ask the user to do it anyway. For now, it is forbiden. //At the product editor, the stock correction button is disabled. KMessageBox::information(this, i18n("The desired product is a group and its stock cannot be modified, try modifying each of its contents."), i18n("Cannot modify stock")); delete myDb; return; } qDebug()<<"New Qty:"<<newStockQty<<" Reason:"<<reason; correctStock(pcode, oldStockQty, newStockQty, reason); delete myDb; } } void iotstockView::correctStock(qulonglong code, double oldStock, double newStock, const QString &reason) { Azahar *myDb = new Azahar; myDb->setDatabase(db); if (!myDb->correctStock(code, oldStock, newStock, reason )) qDebug()<<myDb->lastError(); else { //Log event. log(loggedUserId,QDate::currentDate(), QTime::currentTime(), i18n("Stock Correction: [Product %1] from %2 to %3. Reason:%4",code,oldStock,newStock, reason)); } delete myDb; } void iotstockView::createUser() { Azahar *myDb = new Azahar; myDb->setDatabase(db); UserInfo info; if (!db.isOpen()) openDB(); if (db.isOpen()) { UserEditor *userEditorDlg = new UserEditor(this); userEditorDlg->setUserRole(roleBasic); //preset as default the basic role //dont allow to scale privilages to supervisors. (or create new admins) userEditorDlg->disableRoles(!adminIsLogged); QPixmap photo; if (userEditorDlg->exec() ) { info.username = userEditorDlg->getUserName(); info.name = userEditorDlg->getRealName(); info.address = userEditorDlg->getAddress(); info.phone = userEditorDlg->getPhone(); info.cell = userEditorDlg->getCell(); photo = userEditorDlg->getPhoto(); info.photo = Misc::pixmap2ByteArray(new QPixmap(photo)); info.role = userEditorDlg->getUserRole(); QByteArray saltBA = Hash::getSalt(); info.salt = QString(saltBA); QString pswdTmp = info.salt+userEditorDlg->getNewPassword(); QByteArray passwdBA = pswdTmp.toLocal8Bit(); info.password = Hash::password2hash(passwdBA); if (!myDb->insertUser(info)) qDebug()<<myDb->lastError(); usersModel->select(); //reload loginWindow's users dlgPassword->reloadUsers(); } delete userEditorDlg; } delete myDb; } void iotstockView::createOffer() { if (db.isOpen()) { PromoEditor *promoEditorDlg = new PromoEditor(this); promoEditorDlg->setDb(db); if (promoEditorDlg->exec() ) { QDate dateStart = promoEditorDlg->getDateStart(); QDate dateEnd = promoEditorDlg->getDateEnd(); OfferInfo offerInfo; offerInfo.productCode = promoEditorDlg->getSelectedProductCode(); offerInfo.discount = promoEditorDlg->getDiscount(); offerInfo.dateStart = dateStart; offerInfo.dateEnd = dateEnd; Azahar *myDb = new Azahar; myDb->setDatabase(db); if ( !myDb->createOffer(offerInfo) ) { qDebug()<<myDb->lastError(); notifierPanel->setSize(350,150); notifierPanel->setOnBottom(false); notifierPanel->showNotification(myDb->lastError(), 6000); } delete myDb; offersModel->select(); } delete promoEditorDlg; } } void iotstockView::createProduct() { if (db.isOpen()) { ProductEditor *prodEditorDlg = new ProductEditor(this, true); prodEditorDlg->setModel(productsModel); prodEditorDlg->setDb(db); prodEditorDlg->enableCode(); prodEditorDlg->setStockQtyReadOnly(false); prodEditorDlg->setAutoCode(true); qulonglong newcode = 0; if (prodEditorDlg->exec()) { int resultado = prodEditorDlg->result(); newcode = prodEditorDlg->getCode(); Azahar *myDb = new Azahar; myDb->setDatabase(db); ProductInfo info; //This switch is for theprodEditorDlg->getPrice() new feature: When adding a new product, if entered code exists, it will be edited. to save time... switch (resultado) { case QDialog::Accepted: case statusNormal: if (prodEditorDlg->isGroup()) { info.stockqty = prodEditorDlg->getGRoupStockMax(); //FIXME!!!! returns 1 info.groupElementsStr = prodEditorDlg->getGroupElementsStr(); info.groupPriceDrop = prodEditorDlg->getGroupPriceDrop(); } else { info.stockqty = prodEditorDlg->getStockQty(); info.groupElementsStr = ""; info.groupPriceDrop = 0; } info.code = newcode; info.alphaCode = prodEditorDlg->getAlphacode(); info.vendorCode = prodEditorDlg->getVendorcode(); info.desc = prodEditorDlg->getDescription(); info.price = prodEditorDlg->getPrice(); info.cost = prodEditorDlg->getCost(); info.purchaseQty = info.stockqty; info.units = prodEditorDlg->getMeasureId(); info.tax = prodEditorDlg->getTax1(); info.extratax= prodEditorDlg->getTax2(); info.photo = Misc::pixmap2ByteArray(new QPixmap(prodEditorDlg->getPhoto())); info.department= prodEditorDlg->getDepartmentId(); info.category= prodEditorDlg->getCategoryId(); info.subcategory= prodEditorDlg->getSubCategoryId(); info.points = prodEditorDlg->getPoints(); //FIXME: NEXT line is temporal remove on 0.8 version info.lastProviderId = 1; //Next lines are for groups info.isAGroup = prodEditorDlg->isGroup(); info.isARawProduct = prodEditorDlg->isRaw(); info.hasUnlimitedStock = prodEditorDlg->hasUnlimitedStock(); info.isNotDiscountable = prodEditorDlg->isNotDiscountable(); if (!myDb->insertProduct(info)) qDebug()<<"ERROR:"<<myDb->lastError(); else { //register the stock purchase! createPurchase(info); } productsModel->select(); break; case statusMod: //Here is not allowed to modify a product... just create new ones... break; case QDialog::Rejected: default: break; } delete myDb; } } setProductsFilter(); } TransactionInfo iotstockView::createPurchase(ProductInfo info) { TransactionInfo tInfo; if (db.isOpen()) { Azahar *myDb = new Azahar; myDb->setDatabase(db); qDebug()<<"Creating Purchase..."; QDate date = QDate::currentDate(); QTime time = QTime::currentTime(); tInfo.type = tBuy; tInfo.amount = info.cost*info.stockqty; //as new product the only stock will be the new created. tInfo.date = date; tInfo.time = time; tInfo.paywith = 0.0; tInfo.changegiven = 0.0; tInfo.paymethod = pCash; tInfo.state = tCompleted; tInfo.userid = 1; tInfo.clientid= 1; tInfo.cardnumber = "-NA-"; tInfo.cardauthnum = "-NA-"; tInfo.itemcount = info.stockqty; tInfo.itemlist = QString("%1/%2").arg(info.code).arg(info.stockqty); tInfo.utility = 0; //FIXME: utility is calculated until products are sold, not before. tInfo.terminalnum = 0; //NOTE: Not really a terminal... from admin computer. tInfo.providerid = 1; //FIXME! tInfo.specialOrders = ""; tInfo.balanceId = 0; //taxes double cWOTax = 0; if (myDb->getConfigTaxIsIncludedInPrice()) cWOTax= (info.cost)/(1+((info.tax+info.extratax)/100)); else cWOTax = info.cost; double tax = cWOTax*info.purchaseQty*(info.tax/100); double tax2= cWOTax*info.purchaseQty*(info.extratax/100); tInfo.totalTax = tax + tax2; //insert into database, getting the tr. number. qulonglong trnum = myDb->insertTransaction(tInfo); tInfo.id = trnum; if ( trnum <= 0 ) qDebug()<<"ERROR: Could not create a Purchase Transaction ::createPurchase()"; else { //log log(loggedUserId, date, time, i18n("Purchase #%4 - %1 x %2 (%3)", info.stockqty, info.desc, info.code, trnum) ); } delete myDb; } return tInfo; } void iotstockView::createMeasure() { if (db.isOpen()) { // int row = ui_mainview.tableMeasures->currentIndex().row(); // if (row==-1) row=0; // if (ui_mainview.stackedWidget->currentIndex() != pBrowseMeasures) // ui_mainview.stackedWidget->setCurrentIndex(pBrowseMeasures); // if (measuresModel->tableName().isEmpty()) setupMeasuresModel(); // // measuresModel->insertRow(row); bool ok=false; QString meas = QInputDialog::getText(this, i18n("New Weight or Measure"), i18n("Enter the new weight or measure to insert:"), QLineEdit::Normal, "", &ok ); if (ok && !meas.isEmpty()) { Azahar *myDb = new Azahar; if (!db.isOpen()) openDB(); myDb->setDatabase(db); if (!myDb->insertMeasure(meas)) qDebug()<<"Error:"<<myDb->lastError(); measuresModel->select(); delete myDb; } } } void iotstockView::createDepartment() { //Launch Edit dialog SubcategoryEditor *scEditor = new SubcategoryEditor(this); //get categories list and populate the dialog with them. Azahar *myDb = new Azahar; myDb->setDatabase(db); QStringList catList; catList << myDb->getCategoriesList(); scEditor->populateList( catList ); scEditor->setCatList(catList); scEditor->setScatList(myDb->getSubCategoriesList()); scEditor->setLabelForName(i18n("New Department:")); scEditor->setLabelForList(i18n("Select the child categories for this department:")); scEditor->setDialogType(1); //department = 1 if ( scEditor->exec() ) { QString depText = scEditor->getName(); QStringList children = scEditor->getChildren(); qDebug()<<" CHILDREN:"<<children; //Create the department if (!myDb->insertDepartment(depText)) { qDebug()<<"Error:"<<myDb->lastError(); delete myDb; return; } qulonglong depId = myDb->getDepartmentId(depText); //create the m2m relations for the new department/categories. foreach(QString cat, children) { //get category id qulonglong cId = myDb->getCategoryId(cat); //create the link [department] --> [category] myDb->insertM2MDepartmentCategory(depId, cId); } } departmentsModel->select(); categoriesModel->select(); subcategoriesModel->select(); updateDepartmentsCombo(); delete myDb; } void iotstockView::createCategory() { //Launch Edit dialog SubcategoryEditor *scEditor = new SubcategoryEditor(this); //get categories list and populate the dialog with them. Azahar *myDb = new Azahar; myDb->setDatabase(db); QStringList catList; catList << myDb->getSubCategoriesList(); scEditor->populateList( catList ); scEditor->setCatList(myDb->getCategoriesList()); scEditor->setScatList(catList); scEditor->setLabelForName(i18n("New Category:")); scEditor->setLabelForList(i18n("Select the child subcategories for this category:")); scEditor->setDialogType(2); //category = 2 if ( scEditor->exec() ) { QString text = scEditor->getName(); QStringList children = scEditor->getChildren(); qDebug()<<" CHILDREN:"<<children; //Create the department if (!myDb->insertCategory(text)) { qDebug()<<"Error:"<<myDb->lastError(); delete myDb; return; } qulonglong cId = myDb->getCategoryId(text); //create the m2m relations for the new department/categories. foreach(QString cat, children) { //get category id qulonglong scId = myDb->getSubCategoryId(cat); //create the link [category] --> [subcategory] myDb->insertM2MCategorySubcategory(cId, scId); } } departmentsModel->select(); categoriesModel->select(); subcategoriesModel->select(); updateCategoriesCombo(); delete myDb; } void iotstockView::updateDepartmentsCombo() { populateDepartmentsHash(); ui_mainview.comboProductsFilterByDepartment->clear(); QHashIterator<QString, int> item(departmentsHash); while (item.hasNext()) { item.next(); ui_mainview.comboProductsFilterByDepartment->addItem(item.key()); } } void iotstockView::updateCategoriesCombo() { populateCategoriesHash(); ui_mainview.comboProductsFilterByCategory->clear(); QHashIterator<QString, int> item(categoriesHash); while (item.hasNext()) { item.next(); ui_mainview.comboProductsFilterByCategory->addItem(item.key()); } } void iotstockView::updateCardTypesCombo() { populateCardTypesHash(); ui_mainview.comboCardTypes->clear(); QHashIterator<QString, int> item(cardTypesHash); while (item.hasNext()) { item.next(); ui_mainview.comboCardTypes->addItem(item.key()); } } void iotstockView::updateSubCategoriesCombo() { populateSubCategoriesHash(); ui_mainview.comboProductsFilterBySubCategory->clear(); QHashIterator<QString, int> item(subcategoriesHash); while (item.hasNext()) { item.next(); ui_mainview.comboProductsFilterBySubCategory->addItem(item.key()); } } void iotstockView::createSubCategory() { bool ok=false; QString c = QInputDialog::getText(this, i18n("New Subcategory"), i18n("Enter the new subcategory:"), QLineEdit::Normal, "", &ok ); if (ok && !c.isEmpty()) { Azahar *myDb = new Azahar; if (!db.isOpen()) openDB(); myDb->setDatabase(db); if (!myDb->insertSubCategory(c)) qDebug()<<"Error:"<<myDb->lastError(); delete myDb; } subcategoriesModel->select(); updateSubCategoriesCombo(); } void iotstockView::createClient() { Azahar *myDb = new Azahar; myDb->setDatabase(db); if (db.isOpen()) { ClientEditor *clientEditorDlg = new ClientEditor(this); ClientInfo info; QPixmap photo; if (clientEditorDlg->exec() ) { info.code = clientEditorDlg->getCode(); info.name = clientEditorDlg->getName(); info.address = clientEditorDlg->getAddress(); info.phone = clientEditorDlg->getPhone(); info.cell = clientEditorDlg->getCell(); photo = clientEditorDlg->getPhoto(); info.points = clientEditorDlg->getPoints(); info.discount = clientEditorDlg->getDiscount(); info.since = QDate::currentDate(); info.photo = Misc::pixmap2ByteArray(new QPixmap(photo)); if (!db.isOpen()) openDB(); if (!myDb->insertClient(info)) qDebug()<<myDb->lastError(); clientsModel->select(); } delete clientEditorDlg; } delete myDb; } void iotstockView::deleteSelectedClient() { if (db.isOpen()) { QModelIndex index = ui_mainview.clientsView->currentIndex(); if (clientsModel->tableName().isEmpty()) setupClientsModel(); if (index == clientsModel->index(-1,-1) ) { KMessageBox::information(this, i18n("Please select a client to delete, then press the delete button again."), i18n("Cannot delete")); } else { QString uname = clientsModel->record(index.row()).value("name").toString(); qulonglong clientId = clientsModel->record(index.row()).value("id").toULongLong(); if (clientId > 1) { int answer = KMessageBox::questionYesNo(this, i18n("Do you really want to delete the client named %1?",uname), i18n("Delete")); if (answer == KMessageBox::Yes) { Azahar *myDb = new Azahar; myDb->setDatabase(db); if (!clientsModel->removeRow(index.row(), index)) { // weird: since some time, removeRow does not work... it worked fine on versions < 0.9 .. bool d = myDb->deleteClient(clientId); qDebug()<<"Deleteing client ("<<clientId<<") manually..."; if (d) qDebug()<<"Deletion succed..."; } clientsModel->submitAll(); clientsModel->select(); delete myDb; } } else KMessageBox::information(this, i18n("Default client cannot be deleted."), i18n("Cannot delete")); } } } void iotstockView::deleteSelectedUser() { if (db.isOpen()) { QModelIndex index = ui_mainview.usersView->currentIndex(); if (usersModel->tableName().isEmpty()) setupUsersModel(); if (index == usersModel->index(-1,-1) ) { KMessageBox::information(this, i18n("Please select a user to delete, then press the delete button again."), i18n("Cannot delete")); //TODO: Present a dialog to select which user to delete... } else { QString uname = usersModel->record(index.row()).value("name").toString(); QString usr = usersModel->record(index.row()).value("username").toString(); if (usr != "admin") { int answer = KMessageBox::questionYesNo(this, i18n("Do you really want to delete the user named %1?",uname), i18n("Delete")); if (answer == KMessageBox::Yes) { Azahar *myDb = new Azahar; myDb->setDatabase(db); qulonglong iD = usersModel->record(index.row()).value("id").toULongLong(); if (!usersModel->removeRow(index.row(), index)) { // weird: since some time, removeRow does not work... it worked fine on versions < 0.9 .. bool d = myDb->deleteUser(iD); qDebug()<<"Deleteing user ("<<iD<<") manually..."; if (d) qDebug()<<"Deletion succed..."; } usersModel->submitAll(); usersModel->select(); delete myDb; } } else KMessageBox::information(this, i18n("Admin user cannot be deleted."), i18n("Cannot delete")); } } } void iotstockView::deleteSelectedOffer() { if (db.isOpen()) { QModelIndex index = ui_mainview.tableBrowseOffers->currentIndex(); if (offersModel->tableName().isEmpty()) setupOffersModel(); if (index == offersModel->index(-1,-1) ) { //NOTE: Hey, I think the word "offer" does not mean what i mean... KMessageBox::information(this, i18n("Please select an offer to delete, then press the delete button again."), i18n("Cannot delete")); //NOTE: Present a dialog to select which user to delete?... } else { int answer = KMessageBox::questionYesNo(this, i18n("Do you really want to delete the selected discount?"), i18n("Delete")); if (answer == KMessageBox::Yes) { //same weird error when deleting offers that the products! :S Azahar *myDb = new Azahar; myDb->setDatabase(db); qulonglong code = offersModel->record(index.row()).value("id").toULongLong(); if (!offersModel->removeRow(index.row(), index)) myDb->deleteOffer(code); offersModel->submitAll(); offersModel->select(); } } } } void iotstockView::deleteSelectedProduct() { if (db.isOpen()) { Azahar *myDb = new Azahar; myDb->setDatabase(db); QModelIndex index; if (ui_mainview.productsView->isHidden()) { index = ui_mainview.productsViewAlt->currentIndex(); } else { index = ui_mainview.productsView->currentIndex(); } if (productsModel->tableName().isEmpty()) setupProductsModel(); if (index == productsModel->index(-1,-1) ) { KMessageBox::information(this, i18n("Please select a product to delete, then press the delete button."), i18n("Cannot delete")); } else { int answer = KMessageBox::questionYesNo(this, i18n("Do you really want to delete the selected product?"), i18n("Delete")); if (answer == KMessageBox::Yes) { //first we obtain the product code to be deleted. qulonglong iD = productsModel->record(index.row()).value("code").toULongLong(); if (!productsModel->removeRow(index.row(), index)) { // weird: since some time, removeRow does not work... it worked fine on versions < 0.9 .. bool d = myDb->deleteProduct(iD); qDebug()<<"Deleteing product ("<<iD<<") manually..."; if (d) qDebug()<<"Deletion succed..."; //on deleteProduct the offers are also deleted. } productsModel->submitAll(); productsModel->select(); } } delete myDb; } } void iotstockView::deleteSelectedMeasure() { if (db.isOpen()) { QModelIndex index = ui_mainview.tableMeasures->currentIndex(); if (measuresModel->tableName().isEmpty()) setupMeasuresModel(); if (index == measuresModel->index(-1,-1) ) { KMessageBox::information(this, i18n("Please select a row to delete, then press the delete button again."), i18n("Cannot delete")); } else { QString measureText = measuresModel->record(index.row()).value("text").toString(); Azahar *myDb = new Azahar; myDb->setDatabase(db); qulonglong measureId = myDb->getMeasureId(measureText); if (measureId > 1) { int answer = KMessageBox::questionYesNo(this, i18n("Do you really want to delete the measure '%1'?", measureText), i18n("Delete")); if (answer == KMessageBox::Yes) { qulonglong iD = measuresModel->record(index.row()).value("id").toULongLong(); if (!measuresModel->removeRow(index.row(), index)) { // weird: since some time, removeRow does not work... it worked fine on versions < 0.9 .. bool d = myDb->deleteMeasure(iD); qDebug()<<"Deleteing Measure ("<<iD<<") manually..."; if (d) qDebug()<<"Deletion succed..."; } measuresModel->submitAll(); measuresModel->select(); } } else KMessageBox::information(this, i18n("Default measure cannot be deleted."), i18n("Cannot delete")); delete myDb; } } } void iotstockView::deleteSelectedDepartment() { if (db.isOpen()) { QModelIndex index = ui_mainview.tableDepartments->currentIndex(); if (departmentsModel->tableName().isEmpty()) setupDepartmentsModel(); if (index == departmentsModel->index(-1,-1) ) { KMessageBox::information(this, i18n("Please select a department to delete, then press the delete button again."), i18n("Cannot delete")); } else { QString text = departmentsModel->record(index.row()).value("text").toString(); Azahar *myDb = new Azahar; myDb->setDatabase(db); qulonglong dId = myDb->getDepartmentId(text); if (dId >0) { int answer = KMessageBox::questionYesNo(this, i18n("Do you really want to delete the department '%1'?", text), i18n("Delete")); if (answer == KMessageBox::Yes) { qulonglong iD = departmentsModel->record(index.row()).value("id").toULongLong(); if (!departmentsModel->removeRow(index.row(), index)) { // weird: since some time, removeRow does not work... it worked fine on versions < 0.9 .. bool d = myDb->deleteDepartment(iD); qDebug()<<"Deleteing Department ("<<iD<<") manually..."; if (d) qDebug()<<"Deletion succed..."; } departmentsModel->submitAll(); departmentsModel->select(); updateDepartmentsCombo(); } } else KMessageBox::information(this, i18n("Default department cannot be deleted."), i18n("Cannot delete")); delete myDb; } } } void iotstockView::deleteSelectedCategory() { if (db.isOpen()) { QModelIndex index = ui_mainview.tableCategories->currentIndex(); if (categoriesModel->tableName().isEmpty()) setupCategoriesModel(); if (index == categoriesModel->index(-1,-1) ) { KMessageBox::information(this, i18n("Please select a category to delete, then press the delete button again."), i18n("Cannot delete")); } else { QString catText = categoriesModel->record(index.row()).value("text").toString(); Azahar *myDb = new Azahar; myDb->setDatabase(db); qulonglong catId = myDb->getCategoryId(catText); if (catId >0) { int answer = KMessageBox::questionYesNo(this, i18n("Do you really want to delete the category '%1'?", catText), i18n("Delete")); if (answer == KMessageBox::Yes) { qulonglong iD = categoriesModel->record(index.row()).value("catid").toULongLong(); if (!categoriesModel->removeRow(index.row(), index)) { // weird: since some time, removeRow does not work... it worked fine on versions < 0.9 .. bool d = myDb->deleteCategory(iD); qDebug()<<"Deleteing Category ("<<iD<<") manually..."; if (d) qDebug()<<"Deletion succed..."; } categoriesModel->submitAll(); categoriesModel->select(); updateCategoriesCombo(); } } else KMessageBox::information(this, i18n("Default category cannot be deleted."), i18n("Cannot delete")); delete myDb; } } } void iotstockView::deleteSelectedSubCategory() { if (db.isOpen()) { QModelIndex index = ui_mainview.tableSubCategories->currentIndex(); if (subcategoriesModel->tableName().isEmpty()) setupSubCategoriesModel(); if (index == subcategoriesModel->index(-1,-1) ) { KMessageBox::information(this, i18n("Please select a subcategory to delete, then press the delete button again."), i18n("Cannot delete")); } else { QString catText = subcategoriesModel->record(index.row()).value("text").toString(); Azahar *myDb = new Azahar; myDb->setDatabase(db); qulonglong catId = myDb->getSubCategoryId(catText); if (catId >0) { int answer = KMessageBox::questionYesNo(this, i18n("Do you really want to delete the subcategory '%1'?", catText), i18n("Delete")); if (answer == KMessageBox::Yes) { qulonglong iD = subcategoriesModel->record(index.row()).value("id").toULongLong(); if (!subcategoriesModel->removeRow(index.row(), index)) { // weird: since some time, removeRow does not work... it worked fine on versions < 0.9 .. bool d = myDb->deleteSubCategory(iD); qDebug()<<"Deleteing SubCategory ("<<iD<<") manually..."; if (d) qDebug()<<"Deletion succed..."; } subcategoriesModel->submitAll(); subcategoriesModel->select(); updateSubCategoriesCombo(); } } else KMessageBox::information(this, i18n("Default subcategory cannot be deleted."), i18n("Cannot delete")); delete myDb; } } } //CASH OUTS void iotstockView::setupCashFlowModel() { openDB(); qDebug()<<"setupcashflow.. after openDB"; if (db.isOpen()) { cashflowModel->setTable("cashflow"); cashflowIdIndex = cashflowModel->fieldIndex("id"); cashflowTypeIndex = cashflowModel->fieldIndex("type"); cashflowDateIndex = cashflowModel->fieldIndex("date"); cashflowTimeIndex= cashflowModel->fieldIndex("time"); cashflowUseridIndex= cashflowModel->fieldIndex("userid"); cashflowReasonIndex = cashflowModel->fieldIndex("reason"); cashflowAmountIndex= cashflowModel->fieldIndex("amount"); cashflowTerminalNumIndex= cashflowModel->fieldIndex("terminalnum"); ui_mainview.cashFlowTable->setModel(cashflowModel); ui_mainview.cashFlowTable->setEditTriggers(QAbstractItemView::NoEditTriggers); cashflowModel->setHeaderData(cashflowIdIndex, Qt::Horizontal, i18n("Id")); cashflowModel->setHeaderData(cashflowTypeIndex, Qt::Horizontal, i18n("Type")); cashflowModel->setHeaderData(cashflowDateIndex, Qt::Horizontal, i18n("Date")); cashflowModel->setHeaderData(cashflowUseridIndex, Qt::Horizontal, i18n("Vendor") ); cashflowModel->setHeaderData(cashflowTimeIndex, Qt::Horizontal, i18n("Time") ); cashflowModel->setHeaderData(cashflowReasonIndex, Qt::Horizontal, i18n("Reason") ); cashflowModel->setHeaderData(cashflowAmountIndex, Qt::Horizontal, i18n("Amount") ); cashflowModel->setHeaderData(cashflowTerminalNumIndex, Qt::Horizontal, i18n("Terminal Num.") ); cashflowModel->setRelation(cashflowUseridIndex, QSqlRelation("users", "id", "username")); cashflowModel->setRelation(cashflowTypeIndex, QSqlRelation("cashflowtypes", "typeid", "text")); ui_mainview.cashFlowTable->setSelectionMode(QAbstractItemView::SingleSelection); cashflowModel->select(); } qDebug()<<"setupCashFlow.. done, "<<cashflowModel->lastError(); } void iotstockView::exportTable() { if (ui_mainview.stackedWidget->currentIndex() == 10) { switch(ui_mainview.stackedWidget2->currentIndex()){ case 0: exportQTableView(ui_mainview.cashFlowTable);break; case 1: exportQTableView(ui_mainview.transactionsTable);break; case 2: exportQTableView(ui_mainview.balancesTable);break; case 3: exportQTableView(ui_mainview.tableSO);break; default:break; } } else { switch(ui_mainview.stackedWidget->currentIndex()){ case pBrowseProduct: exportQTableView(ui_mainview.productsViewAlt);break; case pBrowseOffers: exportQTableView(ui_mainview.tableBrowseOffers);break; case pBrowseUsers: exportQTableView(ui_mainview.usersView);break; case pBrowseMeasures: exportQTableView(ui_mainview.tableMeasures);break; case pBrowseCategories: exportQTableView(ui_mainview.tableCategories);break; case pBrowseSubCategories: exportQTableView(ui_mainview.tableSubCategories);break; case pBrowseClients: exportQTableView(ui_mainview.clientsView);break; //case pBrowseTransactions: exportQTableView(ui_mainview.transactionsTable);break; //case pBrowseBalances: exportQTableView(ui_mainview.balancesTable);break; //case pBrowseCashFlow: exportQTableView(ui_mainview.cashFlowTable);break; //case pCustomReports: exportQTableView(ui_mainview.customReportsView);break; default:break; } } } void iotstockView::exportQTableView(QAbstractItemView *tableview) { if (tableview->model()){ const QAbstractItemModel *model = tableview->model(); QString fileName = QFileDialog::getSaveFileName(this, i18n("Save As"),"",i18n("CSV files (*.csv)")); if (fileName != ""){ QFile file(fileName); if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) return; QTextStream out(&file); // Headers for (int j=0;j<model->columnCount();j++){ out << "\"" << model->headerData(j, Qt::Horizontal, Qt::DisplayRole).toString() << "\";"; } out << "\n"; // Data QProgressDialog progress(i18n("Exporting data..."), i18n("Abort"), 0, model->rowCount(), this); progress.setWindowModality(Qt::WindowModal); // If there're more than 1 row selected, then export only this rows QModelIndexList selected = tableview->selectionModel()->selectedRows(); if (selected.count()>1){ for (int i=0;i<selected.count();i++){ for (int j=0;j<model->columnCount();j++){ out << "\"" << model->data(model->index(selected.at(i).row(), j)).toString() << "\";"; } out <<"\n"; } }else{ // export everything in the model for (int i=0;i<model->rowCount();i++){ progress.setValue(i); if (progress.wasCanceled()) break; for (int j=0;j<model->columnCount();j++){ out << "\"" << model->data(model->index(i, j)).toString() << "\";"; } out <<"\n"; } } file.close(); progress.setValue(model->rowCount()); //if (KMessageBox::questionYesNo(this, i18n("Data exported succesfully to %1.\n\n Would you like to open it?").arg(fileName), i18n("Finished")) == KMessageBox::Yes ){ // system(QString("oocalc \""+fileName+ "\"").toLatin1()); } } } // Report printing... void iotstockView::reportActivated(QListWidgetItem *item) { if ( item == itmEndOfMonth ) { printEndOfMonth(); // this is for the end of the month, all terminals. } else if ( item == itmGralEndOfDay ) { printGralEndOfDay(); // this is for end of day of all terminals. } else if ( item == itmEndOfDay ) { printEndOfDay(); } else if ( item == itmPrintSoldOutProducts ) { printSoldOutProducts(); } else if ( item == itmPrintLowStockProducts ) { printLowStockProducts(); } else if ( item == itmPrintStock ) { printStock(); } // } else if ( item == itmPrintBalance ) { // printBalance(); // } } void iotstockView::printGralEndOfDay() { Azahar *myDb = new Azahar; myDb->setDatabase(db); // Get every transaction from all day, calculate sales, profit, and profit margin (%). AmountAndProfitInfo amountProfit; PrintEndOfDayInfo pdInfo; QList<TransactionInfo> transactionsList; amountProfit = myDb->getDaySalesAndProfit(); transactionsList = myDb->getDayTransactions(); //all terminals pdInfo.storeName = myDb->getConfigStoreName(); pdInfo.storeAddr = myDb->getConfigStoreAddress(); pdInfo.storeLogo = myDb->getConfigStoreLogo(); pdInfo.thTitle = i18n("End of day report"); pdInfo.thTicket = i18n("Id"); pdInfo.salesPerson = ""; pdInfo.terminal = i18n("All Terminals"); pdInfo.thDate = KGlobal::locale()->formatDateTime(QDateTime::currentDateTime(), KLocale::LongDate); pdInfo.thTime = i18n("Time"); pdInfo.thAmount = i18n("Amount"); pdInfo.thProfit = i18n("Profit"); pdInfo.thPayMethod = i18n("Method"); pdInfo.thTotalTaxes= i18n("Total taxes collected today: "); pdInfo.logoOnTop = myDb->getConfigLogoOnTop(); pdInfo.thTotalSales = KGlobal::locale()->formatMoney(amountProfit.amount, QString(), 2); pdInfo.thTotalProfit = KGlobal::locale()->formatMoney(amountProfit.profit, QString(), 2); QStringList lines; //for dotmatrix printers on /dev ports lines.append(pdInfo.thTitle); lines.append(pdInfo.thDate); lines.append(pdInfo.terminal); lines.append(pdInfo.thTicket+" "+pdInfo.thTime+ pdInfo.thAmount+" "+pdInfo.thProfit+" "+pdInfo.thPayMethod); //each transaction... double tTaxes = 0; for (int i = 0; i < transactionsList.size(); ++i) { QLocale localeForPrinting; // needed to convert double to a string better TransactionInfo info = transactionsList.at(i); qDebug()<<" transactions on end of day: i="<<i<<" ID:"<<info.id; QString tid = QString::number(info.id); QString hour = info.time.toString("hh:mm"); QString amount = localeForPrinting.toString(info.amount,'f',2); QString profit = localeForPrinting.toString(info.utility, 'f', 2); QString payMethod; payMethod = myDb->getPayTypeStr(info.paymethod);//using payType methods QString line = tid +"|"+ hour +"|"+ amount +"|"+ profit +"|"+ payMethod; pdInfo.trLines.append(line); lines.append(tid+" "+hour+" "+ amount+" "+profit+" "+payMethod); tTaxes += info.totalTax; qDebug()<<"total sale:"<<info.amount<<" taxes this sale:"<<info.totalTax<<" accumulated taxes:"<<tTaxes; } //for each item lines.append(i18n("Total Sales : %1",pdInfo.thTotalSales)); lines.append(i18n("Total Profit: %1",pdInfo.thTotalProfit)); //add taxes amount pdInfo.thTotalTaxes += KGlobal::locale()->formatMoney(tTaxes, QString(), 2); if (Settings::smallTicketDotMatrix()) { // dot matrix printer QString printerFile=Settings::printerDevice(); if (printerFile.length() == 0) printerFile="/dev/lp0"; QString printerCodec=Settings::printerCodec(); qDebug()<<"[Printing report on "<<printerFile<<"]"; qDebug()<<lines.join("\n"); PrintDEV::printSmallBalance(printerFile, printerCodec, lines.join("\n")); } else if (Settings::smallTicketCUPS()) { qDebug()<<"[Printing report on CUPS small size]"; QPrinter printer; printer.setFullPage( true ); QPrintDialog printDialog( &printer ); printDialog.setWindowTitle(i18n("Print end of day report")); if ( printDialog.exec() ) { PrintCUPS::printSmallEndOfDay(pdInfo, printer); } else { //NOTE: This is a proposition: // If the dialog is accepted (ok), then we print what the user choosed. Else, we print to a file (PDF). // The user can press ENTER when dialog appearing if the desired printer is the default (or the only). qDebug()<<"User cancelled printer dialog. We export ticket to a file."; QString fn = QString("%1/iotpos-printing/").arg(QDir::homePath()); QDir dir; if (!dir.exists(fn)) dir.mkdir(fn); fn = fn+QString("GeneralEndOfDay__%1.pdf").arg(QDateTime::currentDateTime().toString("dd-MMM-yy")); qDebug()<<fn; printer.setOutputFileName(fn); printer.setPageMargins(0,0,0,0,QPrinter::Millimeter); printer.setPaperSize(QSizeF(72,200), QPrinter::Millimeter); //setting small ticket paper size. 72mm x 200mm PrintCUPS::printSmallEndOfDay(pdInfo, printer); } } else { //big printer qDebug()<<"[Printing report on CUPS big size]"; QPrinter printer; printer.setFullPage( true ); QPrintDialog printDialog( &printer ); printDialog.setWindowTitle(i18n("Print end of day report")); if ( printDialog.exec() ) { PrintCUPS::printBigEndOfDay(pdInfo, printer); } } delete myDb; } void iotstockView::printEndOfDay() { Azahar *myDb = new Azahar; myDb->setDatabase(db); //first get the terminal number for the end of day InputDialog *dlg = new InputDialog(this, true, dialogTerminalNum, i18n("Enter the Terminal number for the end of day, then press <ENTER> to accept, <ESC> to cancel")); bool ok = false; qulonglong terminalNum = 0; //NOTE: InputDialog has an int validator for a qulonglong variable. Check if there is a QULONGLONGVALIDATOR FIXME at inputdialog.cpp:121 if (dlg->exec()) { terminalNum = dlg->iValue; ok = true; } if (ok) { // Get every transaction from all day, calculate sales, profit, and profit margin (%). AmountAndProfitInfo amountProfit; PrintEndOfDayInfo pdInfo; QList<TransactionInfo> transactionsList; amountProfit = myDb->getDaySalesAndProfit(); transactionsList = myDb->getDayTransactions(terminalNum); if (transactionsList.count() < 1) { //hey, if there are no transactions, why print it? qDebug()<<"Nothing to print!"; KNotification *notify = new KNotification(i18n("No transactions to print!"), this); notify->setText(i18n("No transactions for terminal #%1 for today.", terminalNum)); QPixmap pixmap = DesktopIcon("dialog-warning",22); notify->setPixmap(pixmap); notify->sendEvent(); return; //just to quit. } pdInfo.storeName = myDb->getConfigStoreName(); pdInfo.storeAddr = myDb->getConfigStoreAddress(); pdInfo.storeLogo = myDb->getConfigStoreLogo(); pdInfo.thTitle = i18n("End of day report"); pdInfo.thTicket = i18n("Id"); pdInfo.salesPerson = myDb->getUserName(transactionsList.at(0).userid); pdInfo.terminal = i18n("terminal # %1 ", terminalNum); pdInfo.thDate = KGlobal::locale()->formatDateTime(QDateTime::currentDateTime(), KLocale::LongDate); pdInfo.thTime = i18n("Time"); pdInfo.thAmount = i18n("Amount"); pdInfo.thProfit = i18n("Profit"); pdInfo.thPayMethod = i18n("Method"); pdInfo.thTotalTaxes= i18n("Total taxes collected for this terminal: "); pdInfo.logoOnTop = myDb->getConfigLogoOnTop(); pdInfo.thTotalSales = KGlobal::locale()->formatMoney(amountProfit.amount, QString(), 2); pdInfo.thTotalProfit = KGlobal::locale()->formatMoney(amountProfit.profit, QString(), 2); QStringList lines; //for dotmatrix printers on /dev ports lines.append(pdInfo.thTitle); lines.append(pdInfo.thDate); lines.append(pdInfo.salesPerson +" / "+ pdInfo.terminal); lines.append(pdInfo.thTicket+" "+pdInfo.thTime+ pdInfo.thAmount+" "+pdInfo.thProfit+" "+pdInfo.thPayMethod); //each transaction... double tTaxes = 0; for (int i = 0; i < transactionsList.size(); ++i) { QLocale localeForPrinting; // needed to convert double to a string better TransactionInfo info = transactionsList.at(i); //qDebug()<<" transactions on end of day: i="<<i<<" ID:"<<info.id; QString tid = QString::number(info.id); QString hour = info.time.toString("hh:mm"); QString amount = localeForPrinting.toString(info.amount,'f',2); QString profit = localeForPrinting.toString(info.utility, 'f', 2); QString payMethod; payMethod = myDb->getPayTypeStr(info.paymethod);//using payType methods QString line = tid +"|"+ hour +"|"+ amount +"|"+ profit +"|"+ payMethod; pdInfo.trLines.append(line); lines.append(tid+" "+hour+" "+ amount+" "+profit+" "+payMethod); tTaxes += info.totalTax; qDebug()<<"total sale:"<<info.amount<<" taxes this sale:"<<info.totalTax<<" accumulated taxes:"<<tTaxes; } //for each item lines.append(i18n("Total Sales : %1",pdInfo.thTotalSales)); lines.append(i18n("Total Profit: %1",pdInfo.thTotalProfit)); //add taxes amount pdInfo.thTotalTaxes += KGlobal::locale()->formatMoney(tTaxes, QString(), 2); if (Settings::smallTicketDotMatrix()) { QString printerFile=Settings::printerDevice(); if (printerFile.length() == 0) printerFile="/dev/lp0"; QString printerCodec=Settings::printerCodec(); qDebug()<<"[Printing report on "<<printerFile<<"]"; qDebug()<<lines.join("\n"); PrintDEV::printSmallBalance(printerFile, printerCodec, lines.join("\n")); } else if (Settings::smallTicketCUPS()) { qDebug()<<"[Printing report on CUPS small size]"; QPrinter printer; printer.setFullPage( true ); QPrintDialog printDialog( &printer ); printDialog.setWindowTitle(i18n("Print end of day report")); if ( printDialog.exec() ) { PrintCUPS::printSmallEndOfDay(pdInfo, printer); } else { //NOTE: This is a proposition: // If the dialog is accepted (ok), then we print what the user choosed. Else, we print to a file (PDF). // The user can press ENTER when dialog appearing if the desired printer is the default (or the only). qDebug()<<"User cancelled printer dialog. We export ticket to a file."; QString fn = QString("%1/iotpos-printing/").arg(QDir::homePath()); QDir dir; if (!dir.exists(fn)) dir.mkdir(fn); fn = fn+QString("endOfDay__%1.pdf").arg(QDateTime::currentDateTime().toString("dd-MMM-yy")); qDebug()<<fn; printer.setOutputFileName(fn); printer.setPageMargins(0,0,0,0,QPrinter::Millimeter); printer.setPaperSize(QSizeF(72,200), QPrinter::Millimeter); //setting small ticket paper size. 72mm x 200mm PrintCUPS::printSmallEndOfDay(pdInfo, printer); } } else { //big printer qDebug()<<"[Printing report on CUPS big size]"; QPrinter printer; printer.setFullPage( true ); QPrintDialog printDialog( &printer ); printDialog.setWindowTitle(i18n("Print end of day report")); if ( printDialog.exec() ) { PrintCUPS::printBigEndOfDay(pdInfo, printer); } } } delete myDb; } void iotstockView::printEndOfMonth() { Azahar *myDb = new Azahar; myDb->setDatabase(db); // Get every transaction from all month, calculate sales, profit, and profit margin (%). AmountAndProfitInfo amountProfit; PrintEndOfDayInfo pdInfo; QList<TransactionInfo> transactionsList; amountProfit = myDb->getMonthSalesAndProfit(); transactionsList = myDb->getMonthTransactions(); //all terminals pdInfo.storeName = myDb->getConfigStoreName(); pdInfo.storeAddr = myDb->getConfigStoreAddress(); pdInfo.storeLogo = myDb->getConfigStoreLogo(); pdInfo.thTitle = i18n("End of Month report"); pdInfo.thTicket = i18n("Id"); pdInfo.salesPerson = ""; pdInfo.terminal = i18n("All Terminals"); pdInfo.thDate = KGlobal::locale()->formatDateTime(QDateTime::currentDateTime(), KLocale::LongDate); pdInfo.thTime = i18n("Time"); pdInfo.thAmount = i18n("Amount"); pdInfo.thProfit = i18n("Profit"); pdInfo.thPayMethod = i18n("Date"); pdInfo.thTotalTaxes= i18n("Total taxes collected for the month: "); pdInfo.logoOnTop = myDb->getConfigLogoOnTop(); pdInfo.thTotalSales = KGlobal::locale()->formatMoney(amountProfit.amount, QString(), 2); pdInfo.thTotalProfit = KGlobal::locale()->formatMoney(amountProfit.profit, QString(), 2); QStringList lines; lines.append(pdInfo.thTitle); lines.append(pdInfo.thDate); lines.append(pdInfo.terminal); lines.append(pdInfo.thTicket+" "+pdInfo.thTime+ pdInfo.thAmount+" "+pdInfo.thProfit+" "+pdInfo.thPayMethod); //each transaction... double tTaxes = 0; for (int i = 0; i < transactionsList.size(); ++i) { QLocale localeForPrinting; // needed to convert double to a string better TransactionInfo info = transactionsList.at(i); qDebug()<<" transactions of the Month: i="<<i<<" ID:"<<info.id; QString tid = QString::number(info.id); QString hour = info.time.toString("hh:mm"); QString amount = localeForPrinting.toString(info.amount,'f',2); QString profit = localeForPrinting.toString(info.utility, 'f', 2); QString payMethod= info.date.toString("MMM d"); //KGlobal::locale()->formatDate(info.date, KLocale::ShortDate); //date instead of paymethod QString line = tid +"|"+ hour +"|"+ amount +"|"+ profit +"|"+ payMethod; pdInfo.trLines.append(line); lines.append(tid+" "+hour+" "+ amount+" "+profit+" "+payMethod); tTaxes += info.totalTax; qDebug()<<"total sale:"<<info.amount<<" taxes this sale:"<<info.totalTax<<" accumulated taxes:"<<tTaxes; } //for each item lines.append(i18n("Total Sales : %1",pdInfo.thTotalSales)); lines.append(i18n("Total Profit: %1",pdInfo.thTotalProfit)); //add taxes amount pdInfo.thTotalTaxes += KGlobal::locale()->formatMoney(tTaxes, QString(), 2); if (Settings::smallTicketDotMatrix()) { QString printerFile=Settings::printerDevice(); if (printerFile.length() == 0) printerFile="/dev/lp0"; QString printerCodec=Settings::printerCodec(); qDebug()<<"[Printing report on "<<printerFile<<"]"; qDebug()<<lines.join("\n"); PrintDEV::printSmallBalance(printerFile, printerCodec, lines.join("\n")); } else if (Settings::smallTicketCUPS()) { qDebug()<<"[Printing report on CUPS small size]"; QPrinter printer; printer.setFullPage( true ); QPrintDialog printDialog( &printer ); printDialog.setWindowTitle(i18n("Print end of Month report")); if ( printDialog.exec() ) { PrintCUPS::printSmallEndOfDay(pdInfo, printer); //uses the same method for end of month } else { //NOTE: This is a proposition: // If the dialog is accepted (ok), then we print what the user choosed. Else, we print to a file (PDF). // The user can press ENTER when dialog appearing if the desired printer is the default (or the only). qDebug()<<"User cancelled printer dialog. We export ticket to a file."; QString fn = QString("%1/iotpos-printing/").arg(QDir::homePath()); QDir dir; if (!dir.exists(fn)) dir.mkdir(fn); fn = fn+QString("endOfMonth__%1.pdf").arg(QDateTime::currentDateTime().toString("dd-MMM-yy")); qDebug()<<fn; printer.setOutputFileName(fn); printer.setPageMargins(0,0,0,0,QPrinter::Millimeter); printer.setPaperSize(QSizeF(72,200), QPrinter::Millimeter); //setting small ticket paper size. 72mm x 200mm PrintCUPS::printSmallEndOfDay(pdInfo, printer); } } else { //big printer qDebug()<<"[Printing report on CUPS big size]"; QPrinter printer; printer.setFullPage( true ); QPrintDialog printDialog( &printer ); printDialog.setWindowTitle(i18n("Print end of Month report")); if ( printDialog.exec() ) { PrintCUPS::printBigEndOfDay(pdInfo, printer); //uses the same method for end of month } } delete myDb; } void iotstockView::printLowStockProducts() { Azahar *myDb = new Azahar; myDb->setDatabase(db); QList<ProductInfo> products = myDb->getLowStockProducts(Settings::mostSoldMaxValue()); // stockqty < maxLimit //Header Information PrintLowStockInfo plInfo; plInfo.storeName = myDb->getConfigStoreName(); plInfo.storeAddr = myDb->getConfigStoreAddress(); plInfo.storeLogo = myDb->getConfigStoreLogo(); plInfo.logoOnTop = myDb->getConfigLogoOnTop(); plInfo.hTitle = i18n("Low Stock Products (< %1)", Settings::mostSoldMaxValue()); plInfo.hDate = KGlobal::locale()->formatDateTime(QDateTime::currentDateTime(), KLocale::LongDate); plInfo.hCode = i18n("Code"); plInfo.hDesc = i18n("Description"); plInfo.hQty = i18n("Stock Qty."); plInfo.hSoldU = i18n("Sold"); plInfo.hUnitStr = i18n("Units"); //each product for (int i = 0; i < products.size(); ++i) { QLocale localeForPrinting; ProductInfo info = products.at(i); QString code = QString::number(info.code); QString stock = localeForPrinting.toString(info.stockqty,'f',2); QString soldU = localeForPrinting.toString(info.soldUnits,'f',2); QString line = code +"|"+ info.desc +"|"+ stock +"|"+ info.unitStr +"|"+ soldU; plInfo.pLines.append(line); } if (Settings::smallTicketDotMatrix()) { // QString printerFile=Settings::printerDevice(); // if (printerFile.length() == 0) printerFile="/dev/lp0"; // QString printerCodec=Settings::printerCodec(); // qDebug()<<"[Printing report on "<<printerFile<<"]"; // qDebug()<<lines.join("\n"); // PrintDEV::printSmallBalance(printerFile, printerCodec, lines.join("\n")); } else if (Settings::smallTicketCUPS()) { qDebug()<<"[Printing report on CUPS small size]"; QPrinter printer; printer.setFullPage( true ); QPrintDialog printDialog( &printer ); printDialog.setWindowTitle(i18n("Print Low Stock Report")); if ( printDialog.exec() ) { PrintCUPS::printSmallLowStockReport(plInfo, printer); } else { //NOTE: This is a proposition: // If the dialog is accepted (ok), then we print what the user choosed. Else, we print to a file (PDF). // The user can press ENTER when dialog appearing if the desired printer is the default (or the only). qDebug()<<"User cancelled printer dialog. We export ticket to a file. :: printLowStockProducts"; QString fn = QString("%1/iotpos-printing/").arg(QDir::homePath()); QDir dir; if (!dir.exists(fn)) dir.mkdir(fn); fn = fn+QString("LowStockReport__%1.pdf").arg(QDateTime::currentDateTime().toString("dd-MMM-yy")); qDebug()<<fn; printer.setOutputFileName(fn); printer.setPageMargins(0,0,0,0,QPrinter::Millimeter); printer.setPaperSize(QSizeF(72,200), QPrinter::Millimeter); //setting small ticket paper size. 72mm x 200mm PrintCUPS::printSmallLowStockReport(plInfo, printer); } } else { //big printer qDebug()<<"[Printing report on CUPS big size]"; QPrinter printer; printer.setFullPage( true ); QPrintDialog printDialog( &printer ); printDialog.setWindowTitle(i18n("Print Low Stock Report")); if ( printDialog.exec() ) { PrintCUPS::printBigLowStockReport(plInfo, printer); } } delete myDb; } //NOTE: The unlimited stock producs will show 99999. void iotstockView::printStock() { Azahar *myDb = new Azahar; myDb->setDatabase(db); QList<ProductInfo> products = myDb->getAllProducts(); // does not return grouped products! //Header Information PrintLowStockInfo plInfo; plInfo.storeName = myDb->getConfigStoreName(); plInfo.storeAddr = myDb->getConfigStoreAddress(); plInfo.storeLogo = myDb->getConfigStoreLogo(); plInfo.logoOnTop = myDb->getConfigLogoOnTop(); plInfo.hTitle = i18n("Product Stock (excluding groups)"); plInfo.hDate = KGlobal::locale()->formatDateTime(QDateTime::currentDateTime(), KLocale::LongDate); plInfo.hCode = i18n("Code"); plInfo.hDesc = i18n("Description"); plInfo.hQty = i18n("Stock Qty."); plInfo.hSoldU = i18n("Sold"); plInfo.hUnitStr = i18n("Units"); //each product for (int i = 0; i < products.size(); ++i) { QLocale localeForPrinting; ProductInfo info = products.at(i); QString code = QString::number(info.code); QString stock = localeForPrinting.toString(info.stockqty,'f',2); QString soldU = localeForPrinting.toString(info.soldUnits,'f',2); QString line = code +"|"+ info.desc +"|"+ stock +"|"+ info.unitStr +"|"+ soldU; plInfo.pLines.append(line); } if (Settings::smallTicketDotMatrix()) { // QString printerFile=Settings::printerDevice(); // if (printerFile.length() == 0) printerFile="/dev/lp0"; // QString printerCodec=Settings::printerCodec(); // qDebug()<<"[Printing report on "<<printerFile<<"]"; // qDebug()<<lines.join("\n"); // PrintDEV::printSmallBalance(printerFile, printerCodec, lines.join("\n")); } else if (Settings::smallTicketCUPS()) { qDebug()<<"[Printing report on CUPS small size]"; QPrinter printer; printer.setFullPage( true ); QPrintDialog printDialog( &printer ); printDialog.setWindowTitle(i18n("Print Low Stock Report")); if ( printDialog.exec() ) { PrintCUPS::printSmallLowStockReport(plInfo, printer); } else { //NOTE: This is a proposition: // If the dialog is accepted (ok), then we print what the user choosed. Else, we print to a file (PDF). // The user can press ENTER when dialog appearing if the desired printer is the default (or the only). qDebug()<<"User cancelled printer dialog. We export ticket to a file. ::PrintStock()"; QString fn = QString("%1/iotpos-printing/").arg(QDir::homePath()); QDir dir; if (!dir.exists(fn)) dir.mkdir(fn); fn = fn+QString("StockReport__%1.pdf").arg(QDateTime::currentDateTime().toString("dd-MMM-yy")); qDebug()<<fn; printer.setOutputFileName(fn); printer.setPageMargins(0,0,0,0,QPrinter::Millimeter); printer.setPaperSize(QSizeF(72,200), QPrinter::Millimeter); //setting small ticket paper size. 72mm x 200mm PrintCUPS::printSmallLowStockReport(plInfo, printer); } } else { //big printer qDebug()<<"[Printing report on CUPS big size]"; QPrinter printer; printer.setFullPage( true ); QPrintDialog printDialog( &printer ); printDialog.setWindowTitle(i18n("Print Low Stock Report")); if ( printDialog.exec() ) { PrintCUPS::printBigLowStockReport(plInfo, printer); } } delete myDb; } void iotstockView::printSoldOutProducts() { Azahar *myDb = new Azahar; myDb->setDatabase(db); QList<ProductInfo> products = myDb->getSoldOutProducts(); //Header Information PrintLowStockInfo plInfo; plInfo.storeName = myDb->getConfigStoreName(); plInfo.storeAddr = myDb->getConfigStoreAddress(); plInfo.storeLogo = myDb->getConfigStoreLogo(); plInfo.logoOnTop = myDb->getConfigLogoOnTop(); plInfo.hTitle = i18n("Sold Out Products"); plInfo.hCode = i18n("Code"); plInfo.hDesc = i18n("Description"); plInfo.hQty = i18n("Stock Qty"); plInfo.hSoldU = i18n("Sold Units"); plInfo.hUnitStr = i18n("Units"); plInfo.hDate = KGlobal::locale()->formatDateTime(QDateTime::currentDateTime(), KLocale::LongDate); //each product for (int i = 0; i < products.size(); ++i) { QLocale localeForPrinting; ProductInfo info = products.at(i); QString code = QString::number(info.code); QString stock = localeForPrinting.toString(info.stockqty,'f',2); QString soldU = localeForPrinting.toString(info.soldUnits,'f',2); QString line = code +"|"+ info.desc +"|"+ stock +"|"+ info.unitStr +"|"+ soldU; plInfo.pLines.append(line); } if (Settings::smallTicketDotMatrix()) { // QString printerFile=Settings::printerDevice(); // if (printerFile.length() == 0) printerFile="/dev/lp0"; // QString printerCodec=Settings::printerCodec(); // qDebug()<<"[Printing report on "<<printerFile<<"]"; // qDebug()<<lines.join("\n"); // PrintDEV::printSmallBalance(printerFile, printerCodec, lines.join("\n")); } else if (Settings::smallTicketCUPS()) { qDebug()<<"[Printing report on CUPS small size]"; QPrinter printer; printer.setFullPage( true ); QPrintDialog printDialog( &printer ); printDialog.setWindowTitle(i18n("Print Sold Out Products")); if ( printDialog.exec() ) { PrintCUPS::printSmallLowStockReport(plInfo, printer); } else { //NOTE: This is a proposition: // If the dialog is accepted (ok), then we print what the user choosed. Else, we print to a file (PDF). // The user can press ENTER when dialog appearing if the desired printer is the default (or the only). qDebug()<<"User cancelled printer dialog. We export ticket to a file. :: soldOutProducts()"; QString fn = QString("%1/iotpos-printing/").arg(QDir::homePath()); QDir dir; if (!dir.exists(fn)) dir.mkdir(fn); fn = fn+QString("SoldOutReport__%1.pdf").arg(QDateTime::currentDateTime().toString("dd-MMM-yy")); qDebug()<<fn; printer.setOutputFileName(fn); printer.setPageMargins(0,0,0,0,QPrinter::Millimeter); printer.setPaperSize(QSizeF(72,200), QPrinter::Millimeter); //setting small ticket paper size. 72mm x 200mm PrintCUPS::printSmallLowStockReport(plInfo, printer); } } else { //big printer qDebug()<<"[Printing report on CUPS big size]"; QPrinter printer; printer.setFullPage( true ); QPrintDialog printDialog( &printer ); printDialog.setWindowTitle(i18n("Print Sold Out Products")); if ( printDialog.exec() ) { PrintCUPS::printBigLowStockReport(plInfo, printer); } } delete myDb; } void iotstockView::printSelectedBalance() { Azahar *myDb = new Azahar; myDb->setDatabase(db); qDebug()<<"Print Selected Balance"; if (db.isOpen()) { QModelIndex index = ui_mainview.balancesTable->currentIndex(); if (balancesModel->tableName().isEmpty()) setupBalancesModel(); if (index == balancesModel->index(-1,-1) ) { KMessageBox::information(this, i18n("Please select a balance to print, then press the print button again."), i18n("Cannot print")); } else { qulonglong bid = balancesModel->record(index.row()).value("id").toULongLong(); //get from database all info. BalanceInfo info = myDb->getBalanceInfo(bid); qDebug()<<"Printing balance id:"<<bid; //print... PrintBalanceInfo pbInfo; pbInfo.thBalanceId = i18n("Balance Id:%1",info.id); pbInfo.storeName = myDb->getConfigStoreName(); pbInfo.storeAddr = myDb->getConfigStoreAddress(); pbInfo.storeLogo = myDb->getConfigStoreLogo(); pbInfo.thTitle = i18n("%1 at Terminal # %2", info.username, info.terminal); pbInfo.thDeposit = i18n("Deposit"); pbInfo.thIn = i18n("In"); pbInfo.thOut = i18n("Out"); pbInfo.thInDrawer = i18n("In Drawer"); pbInfo.thTitleDetails = i18n("Transactions Details"); pbInfo.thTrId = i18n("Id"); pbInfo.thTrTime = i18n("Time"); pbInfo.thTrAmount = i18n("Amount"); pbInfo.thTrPaidW = i18n("Paid"); pbInfo.thTrPayMethod=i18n("Method"); pbInfo.startDate = i18n("Start: %1",KGlobal::locale()->formatDateTime(info.dateTimeStart, KLocale::LongDate)); pbInfo.endDate = i18n("End : %1",KGlobal::locale()->formatDateTime(info.dateTimeEnd, KLocale::LongDate)); //Qty's pbInfo.initAmount = KGlobal::locale()->formatMoney(info.initamount, QString(), 2); pbInfo.inAmount = KGlobal::locale()->formatMoney(info.in, QString(), 2); pbInfo.outAmount = KGlobal::locale()->formatMoney(info.out, QString(), 2); pbInfo.cashAvailable=KGlobal::locale()->formatMoney(info.cash, QString(), 2); pbInfo.logoOnTop = myDb->getConfigLogoOnTop(); pbInfo.thTitleCFDetails = i18n("Cash flow Details"); pbInfo.thCFType = i18n("Type"); pbInfo.thCFReason = i18n("Reason"); pbInfo.thCFDate = i18n("Time"); //TXT for dot-matrix printer QStringList lines; QString line; lines.append(i18n("%1 at Terminal # %2", info.username, info.terminal)); line = QString(KGlobal::locale()->formatDateTime(info.dateTimeEnd, KLocale::LongDate)); lines.append(line); lines.append("----------------------------------------"); line = QString("%1 %2").arg(i18n("Initial Amount deposited:")).arg(KGlobal::locale()->formatMoney(info.initamount, QString(), 2)); lines.append(line); line = QString("%1 :%2, %3 :%4") .arg(i18n("In")) .arg(KGlobal::locale()->formatMoney(info.in, QString(), 2)) .arg(i18n("Out")) .arg(KGlobal::locale()->formatMoney(info.out, QString(), 2)); lines.append(line); line = QString(" %1 %2").arg(KGlobal::locale()->formatMoney(info.cash, QString(), 2)).arg(i18n("In Drawer")); lines.append(line); line = QString("----------%1----------").arg(i18n("Transactions Details")); lines.append(line); line = QString("%1 %2 %3").arg(i18n("Id")).arg(i18n("Amount")).arg(i18n("Paid")); lines.append(line); lines.append("---------- ---------- ----------"); QStringList transactionsByUser = info.transactions.split(","); QStringList trList; QString dId; QString dAmount; QString dHour; QString dMinute; QString dPaidWith; QString dPayMethod; for (int i = 0; i < transactionsByUser.size(); ++i) { qulonglong idNum = transactionsByUser.at(i).toULongLong(); TransactionInfo info; info = myDb->getTransactionInfo(idNum); dId = QString::number(info.id); dAmount = QString::number(info.amount); dHour = info.time.toString("hh"); dMinute = info.time.toString("mm"); dPaidWith = QString::number(info.paywith); QString tmp = QString("%1|%2|%3|%4") .arg(dId) .arg(dHour+":"+dMinute) .arg(KGlobal::locale()->formatMoney(info.amount, QString(), 2)) .arg(KGlobal::locale()->formatMoney(info.paywith, QString(), 2)); while (dId.length()<10) dId = dId.insert(dId.length(), ' '); while (dAmount.length()<14) dAmount = dAmount.insert(dAmount.length(), ' '); while ((dHour+dMinute).length()<6) dMinute = dMinute.insert(dMinute.length(), ' '); while (dPaidWith.length()<10) dPaidWith = dPaidWith.insert(dPaidWith.length(), ' '); dPayMethod = myDb->getPayTypeStr(info.paymethod);//using payType methods line = QString("%1 %2 %3") .arg(dId) .arg(dAmount) .arg(dPayMethod); lines.append(line); tmp += "|"+dPayMethod; trList.append( tmp ); } //for pbInfo.trList = trList; //TODO: FIXME to save and retrieve from db the cashflow info for user work lapse. // We can obtain it from cashflow table using a data BETWEEN select //get CashOut list and its info... QStringList cfList; cfList.clear(); QList<CashFlowInfo> cashflowInfoList = myDb->getCashFlowInfoList(info.dateTimeStart, info.dateTimeEnd); foreach(CashFlowInfo cfInfo, cashflowInfoList) { QString amountF = KGlobal::locale()->formatMoney(cfInfo.amount); QString dateF = KGlobal::locale()->formatTime(cfInfo.time); QString data = QString::number(cfInfo.id) + "|" + cfInfo.typeStr + "|" + cfInfo.reason + "|" + amountF + "|" + dateF; cfList.append(data); qDebug()<<"cashflow:"<<data; } pbInfo.cfList = cfList; if (Settings::smallTicketDotMatrix()) { //print it on the /dev/lpXX... send lines to print if (Settings::printBalances()) { QString printerFile=Settings::printerDevice(); if (printerFile.length() == 0) printerFile="/dev/lp0"; QString printerCodec=Settings::printerCodec(); qDebug()<<"[Printing balance on "<<printerFile<<"]"; PrintDEV::printSmallBalance(printerFile, printerCodec, lines.join("\n")); } } else if (Settings::printBalances()) { //print it on cups... send pbInfo instead QPrinter printer; printer.setFullPage( true ); QPrintDialog printDialog( &printer ); printDialog.setWindowTitle(i18n("Print Balance")); if ( printDialog.exec() ) { PrintCUPS::printSmallBalance(pbInfo, printer); } else { //NOTE: This is a proposition: // If the dialog is accepted (ok), then we print what the user choosed. Else, we print to a file (PDF). // The user can press ENTER when dialog appearing if the desired printer is the default (or the only). qDebug()<<"User cancelled printer dialog. We export ticket to a file."; QString fn = QString("%1/iotpos-printing/").arg(QDir::homePath()); QDir dir; if (!dir.exists(fn)) dir.mkdir(fn); fn = fn+QString("balance-%1__%2.pdf").arg(info.id).arg(info.dateTimeStart.date().toString("dd-MMM-yy")); qDebug()<<fn; printer.setOutputFileName(fn); printer.setPageMargins(0,0,0,0,QPrinter::Millimeter); printer.setPaperSize(QSizeF(72,200), QPrinter::Millimeter); //setting small ticket paper size. 72mm x 200mm PrintCUPS::printSmallBalance(pbInfo, printer); } } //end print } } delete myDb; } //LOGS void iotstockView::log(const qulonglong &uid, const QDate &date, const QTime &time, const QString &text) { Azahar *myDb = new Azahar; myDb->setDatabase(db); myDb->insertLog(uid, date, time, "[IOTSTOCK] "+text); logsModel->select(); delete myDb; } void iotstockView::showLogs() { ui_mainview.stackedWidget->setCurrentIndex(pBrowseLogs); if (logsModel->tableName().isEmpty()) setupLogsModel(); ui_mainview.headerLabel->setText(i18n("Events Log")); ui_mainview.headerImg->setPixmap((DesktopIcon("view-pim-tasks-pending",22))); } void iotstockView::setupLogsModel() { openDB(); qDebug()<<"setup logs msgs model.. after openDB"; if (db.isOpen()) { logsModel->setTable("logs"); int logIdIndex = logsModel->fieldIndex("id"); int logUserIndex = logsModel->fieldIndex("userid"); int logActionIndex = logsModel->fieldIndex("action"); int logDateIndex = logsModel->fieldIndex("date"); int logTimeIndex = logsModel->fieldIndex("time"); ui_mainview.logTable->setModel(logsModel); logsModel->setHeaderData(logUserIndex, Qt::Horizontal, i18n("User")); logsModel->setHeaderData(logDateIndex, Qt::Horizontal, i18n("Date")); logsModel->setHeaderData(logTimeIndex, Qt::Horizontal, i18n("Time")); logsModel->setHeaderData(logActionIndex, Qt::Horizontal, i18n("Event")); ui_mainview.logTable->setColumnHidden(logIdIndex, true); logsModel->setRelation(logUserIndex, QSqlRelation("users", "id", "name")); ui_mainview.logTable->setSelectionMode(QAbstractItemView::SingleSelection); ui_mainview.logTable->setEditTriggers(QAbstractItemView::NoEditTriggers); logsModel->select(); } ui_mainview.logTable->resizeColumnsToContents(); qDebug()<<"setup Logs.. done, "<<logsModel->lastError(); } //Random Messages void iotstockView::setupRandomMsgModel() { openDB(); qDebug()<<"setup random msgs model.. after openDB"; if (db.isOpen()) { randomMsgModel->setTable("random_msgs"); int randomMsgIdIndex = randomMsgModel->fieldIndex("id"); int randomMsgMessageIndex = randomMsgModel->fieldIndex("message"); int randomMsgSeasonIndex = randomMsgModel->fieldIndex("season"); int randomMsgCountIndex = randomMsgModel->fieldIndex("count"); ui_mainview.randomMsgTable->setModel(randomMsgModel); randomMsgModel->setHeaderData(randomMsgMessageIndex, Qt::Horizontal, i18n("Message")); randomMsgModel->setHeaderData(randomMsgSeasonIndex, Qt::Horizontal, i18n("Month")); ui_mainview.randomMsgTable->setColumnHidden(randomMsgIdIndex, true); ui_mainview.randomMsgTable->setColumnHidden(randomMsgCountIndex, true); ui_mainview.randomMsgTable->setSelectionMode(QAbstractItemView::SingleSelection); randomMsgModel->select(); //TODO:validator for months //ui_mainview.randomMsgTable->setItemDelegate( ); } ui_mainview.randomMsgTable->resizeColumnsToContents(); //qDebug()<<"setup RandomMsg.. done, "<<randomMsgModel->lastError(); } void iotstockView::createRandomMsg() { if (db.isOpen()) { InputDialog *dlg = new InputDialog(this, true, dialogTicketMsg, i18n("Enter the new ticket message."), 1, 12); if (dlg->exec()) { Azahar *myDb = new Azahar; if (!db.isOpen()) openDB(); myDb->setDatabase(db); if (!myDb->insertRandomMessage(dlg->reason, dlg->iValue)) qDebug()<<"Error:"<<myDb->lastError(); randomMsgModel->select(); delete myDb; } } } void iotstockView::createCurrency() { if (db.isOpen()) { InputDialog *dlg = new InputDialog(this, false, dialogCurrency, i18n("Enter the new currency")); if (dlg->exec()) { Azahar *myDb = new Azahar; if (!db.isOpen()) openDB(); myDb->setDatabase(db); if (!myDb->insertCurrency(dlg->reason, dlg->dValue)) qDebug()<<"Error:"<<myDb->lastError(); currenciesModel->select(); delete myDb; } } } void iotstockView::deleteSelectedCurrency() { if (db.isOpen()) { QModelIndex index = ui_mainview.tableCurrencies->currentIndex(); if (currenciesModel->tableName().isEmpty()) setupCurrenciesModel(); if (index == currenciesModel->index(-1,-1) ) { KMessageBox::information(this, i18n("Please select a row to delete, then press the delete button again."), i18n("Cannot delete")); } else { QString text = currenciesModel->record(index.row()).value("name").toString(); Azahar *myDb = new Azahar; myDb->setDatabase(db); qulonglong cId = myDb->getCurrency(text).id; if (cId > 1) { int answer = KMessageBox::questionYesNo(this, i18n("Do you really want to delete the currency '%1'?", text), i18n("Delete")); if (answer == KMessageBox::Yes) { qulonglong iD = currenciesModel->record(index.row()).value("id").toULongLong(); if (!currenciesModel->removeRow(index.row(), index)) { bool d = myDb->deleteCurrency(iD); qDebug()<<"Deleteing currency ("<<iD<<") manually..."; if (d) qDebug()<<"Deletion succed..."; } currenciesModel->submitAll(); currenciesModel->select(); } } else KMessageBox::information(this, i18n("Default currencies cannot be deleted."), i18n("Cannot delete")); delete myDb; } } } void iotstockView::reSelectModels() { qDebug()<<"Updating Models from database..."; if ( modelsAreCreated() ) { productsModel->select(); measuresModel->select(); clientsModel->select(); usersModel->select(); transactionsModel->select(); categoriesModel->select(); offersModel->select(); balancesModel->select(); cashflowModel->select(); specialOrdersModel->select(); randomMsgModel->select(); logsModel->select(); currenciesModel->select(); } } void iotstockView::departmentsOnSelected(const QModelIndex &index) { if (db.isOpen()) { //getting data from model... const QAbstractItemModel *model = index.model(); int row = index.row(); QModelIndex indx = model->index(row, departmentsModel->fieldIndex("id")); qulonglong depId = model->data(indx, Qt::DisplayRole).toULongLong(); indx = model->index(row, departmentsModel->fieldIndex("text")); QString name = model->data(indx, Qt::DisplayRole).toString(); QStringList children; Azahar *myDb = new Azahar; myDb->setDatabase(db); //get child categories children = myDb->getCategoriesList(depId);//get the categories whose parent is depId. qDebug()<<"DEPARTMENT "<<name<<" ["<<depId<<"]"<<" CHILDREN:"<<children; //launch the editor. SubcategoryEditor *scEditor = new SubcategoryEditor(this); scEditor->setDb(db); scEditor->setCatList( children ); scEditor->setScatList( myDb->getSubCategoriesList() ); scEditor->populateList( myDb->getCategoriesList(), children ); scEditor->setDialogType(1); //department = 1 scEditor->setLabelForName(i18n("Department:")); scEditor->setLabelForList(i18n("Child categories for this department:")); scEditor->setName(name); //check for any changes... if ( scEditor->exec() ) { QString newName = scEditor->getName(); QStringList newChildren = scEditor->getChildren(); qDebug()<<"NEW NAME:"<<newName<<" CHILDREN:"<<newChildren; //first see if the name changed. if (name != newName) { //rename the department myDb->updateDepartment(depId, newName); } //then see if any category has been added or any removed if ( children != newChildren ){ qDebug()<<"children != newChildren ..."; //condicinoes a checar: Es nueva, No esta pero estaba, foreach(QString e, newChildren) { //check if the child is in the old children. if (children.contains(e)){ ///old list contains 'e', it means it already was on the list, we do not need to do anything. } else { ///old list does not contains 'e', this means that 'e' is a new child. //get its ID to make m2m connections. qulonglong catId = myDb->getCategoryId(e); qDebug()<<"NEW ELEMENT: "<<e<<" ["<<catId<<"]"; myDb->insertM2MDepartmentCategory(depId, catId); } } //until here, we examined newChildren, but we need to know if any of the children was REMOVED (not present in newChildren) //this is not a efficient way, we are duplicating the comparisons. foreach(QString e, children){ if ( !newChildren.contains(e) ){ // 'e' is NOT in the newChildren then remove the m2m connection. qulonglong catId = myDb->getCategoryId(e); if (!myDb->m2mDepartmentCategoryRemove(depId, catId)){ qDebug()<<"m2m Department -> Category could not be removed. "<<name<<"->"<<e<<" |"<<myDb->lastError(); } } }//for each children }//if children != newChildren }//if scEditor->exec departmentsModel->select(); delete myDb; } } void iotstockView::categoriesOnSelected(const QModelIndex &index) { if (db.isOpen()) { //getting data from model... const QAbstractItemModel *model = index.model(); int row = index.row(); QModelIndex indx = model->index(row, categoriesModel->fieldIndex("catid")); qulonglong catId = model->data(indx, Qt::DisplayRole).toULongLong(); indx = model->index(row, categoriesModel->fieldIndex("text")); QString name = model->data(indx, Qt::DisplayRole).toString(); QStringList children; Azahar *myDb = new Azahar; myDb->setDatabase(db); //get child categories children = myDb->getSubCategoriesList(catId);//get the categories whose parent is depId. qDebug()<<"CATEGORY "<<name<<" ["<<catId<<"]"<<" CHILDREN:"<<children; //launch the editor. QStringList subcat = myDb->getSubCategoriesList(); SubcategoryEditor *scEditor = new SubcategoryEditor(this); scEditor->setDb(db); scEditor->setCatList( myDb->getCategoriesList() ); scEditor->setScatList( subcat ); scEditor->populateList( subcat, children ); scEditor->setDialogType(1); //department = 1 scEditor->setLabelForName(i18n("Category:")); scEditor->setLabelForList(i18n("Child subcategories for this category:")); scEditor->setName(name); //check for any changes... if ( scEditor->exec() ) { QString newName = scEditor->getName(); QStringList newChildren = scEditor->getChildren(); qDebug()<<"NEW NAME:"<<newName<<" CHILDREN:"<<newChildren; //first see if the name changed. if (name != newName) { //rename the department myDb->updateCategory(catId, newName); } //then see if any category has been added or any removed if ( children != newChildren ){ qDebug()<<"children != newChildren ..."; //condicinoes a checar: Es nueva, No esta pero estaba, foreach(QString e, newChildren) { //check if the child is in the old children. if (children.contains(e)){ ///old list contains 'e', it means it already was on the list, we do not need to do anything. } else { ///old list does not contains 'e', this means that 'e' is a new child. //get its ID to make m2m connections. qulonglong scatId = myDb->getSubCategoryId(e); qDebug()<<"NEW ELEMENT: "<<e<<" ["<<scatId<<"]"; myDb->insertM2MCategorySubcategory(catId, scatId); } } //until here, we examined newChildren, but we need to know if any of the children was REMOVED (not present in newChildren) //this is not a efficient way, we are duplicating the comparisons. foreach(QString e, children){ if ( !newChildren.contains(e) ){ // 'e' is NOT in the newChildren then remove the m2m connection. qulonglong scatId = myDb->getSubCategoryId(e); if (!myDb->m2mCategorySubcategoryRemove(catId, scatId)){ qDebug()<<"m2m Category -> SubCategory could not be removed. "<<name<<"->"<<e<<" |"<<myDb->lastError(); } } }//for each children }//if children != newChildren }//if scEditor->exec categoriesModel->select(); delete myDb; } } #include "iotstockview.moc"
191,634
C++
.cpp
3,875
43.277419
287
0.692236
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
752,825
promoeditor.cpp
hiramvillarreal_iotpos/iotstock/src/promoeditor.cpp
/************************************************************************** * Copyright © 2013-2015 by Hiram R. Villarreal * * hiramvillarreal.ap@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include <KLocale> #include <KMessageBox> #include <KFileDialog> #include <QByteArray> #include "promoeditor.h" #include "../../dataAccess/azahar.h" PromoEditorUI::PromoEditorUI( QWidget *parent ) : QFrame( parent ) { setupUi( this ); } PromoEditor::PromoEditor( QWidget *parent ) : KDialog( parent ) { ui = new PromoEditorUI( this ); setMainWidget( ui ); setCaption( i18n("Discounts Editor") ); setButtons( KDialog::Ok|KDialog::Cancel ); // BFB: New spinboxPrice: I've created new slots to control when discount, price or product are changed connect( ui->spinboxDiscount, SIGNAL(valueChanged(double)),this, SLOT(discountChanged()) ); connect( ui->spinboxPrice, SIGNAL(/*editingFinished*/valueChanged(double)),this, SLOT(priceChanged()) ); connect(ui->offersDatepickerStart, SIGNAL(dateChanged(const QDate & )), this, SLOT(checkValid())); connect(ui->offersDatepickerEnd, SIGNAL(dateChanged(const QDate & )), this, SLOT(checkValid())); connect(ui->productsList, SIGNAL(clicked(const QModelIndex &)), this, SLOT(productChanged())); connect(ui->productsList, SIGNAL(activated(const QModelIndex &)), this, SLOT(productChanged())); connect(ui->productsList, SIGNAL(entered(const QModelIndex &)), this, SLOT(productChanged())); enableButtonOk(false); QTimer::singleShot(750, this, SLOT(checkValid())); } PromoEditor::~PromoEditor() { delete ui; } void PromoEditor::setDb(QSqlDatabase database) { db = database; if (!db.isOpen()) db.open(); populateCategoriesCombo(); //create the model model = new QSqlRelationalTableModel(); setupModel(); ui->productsList->setCurrentIndex(model->index(-1, -1)); connect( ui->chByName, SIGNAL(toggled(bool)), SLOT(setFilter())); connect( ui->chByCat, SIGNAL(toggled(bool)), SLOT(setFilter())); connect( ui->editName, SIGNAL(textEdited(const QString &)), SLOT(setFilter())); connect( ui->comboCategory, SIGNAL(currentIndexChanged( int ) ), SLOT(setFilter())); } void PromoEditor::populateCategoriesCombo() { Azahar *myDb = new Azahar; myDb->setDatabase(db); ui->comboCategory->addItems(myDb->getCategoriesList()); } //FIXME: How to detect when a product does not exists? code=-1, but here codes are unsigned, to allow a broader range. qulonglong PromoEditor::getSelectedProductCode() { qulonglong code=0; Azahar *myDb = new Azahar; myDb->setDatabase(db); QModelIndex index = ui->productsList->currentIndex(); if (index.isValid()) { QString data = model->data(index, Qt::DisplayRole).toString(); code = myDb->getProductCode(data); } return code; } // BFB: New spinboxPrice. We need to obtain product price, and then calculate offer price void PromoEditor::productChanged() { qulonglong code = getSelectedProductCode(); if (code != 0){ Azahar *myDb = new Azahar; myDb->setDatabase(db); ProductInfo info = myDb->getProductInfo(QString::number(code)); ui->spinboxPrice->setValue(info.price*(100.0-ui->spinboxDiscount->value())/100); } checkValid(); } // BFB: New spinboxPrice. Calculate offer product price from percentage void PromoEditor::discountChanged() { if (isProductSelected()){ qulonglong code = getSelectedProductCode(); if (code != 0){ Azahar *myDb = new Azahar; myDb->setDatabase(db); ProductInfo info = myDb->getProductInfo(QString::number(code)); ui->spinboxPrice->setValue(info.price*(100.0-ui->spinboxDiscount->value())/100); } } checkValid(); } // BFB: New spinboxPrice. Calculate offer percentage from offer price void PromoEditor::priceChanged() { if (isProductSelected()){ qulonglong code = getSelectedProductCode(); if (code != 0){ Azahar *myDb = new Azahar; myDb->setDatabase(db); ProductInfo info = myDb->getProductInfo(QString::number(code)); ui->spinboxDiscount->setValue(100.0-(ui->spinboxPrice->value()*100/info.price)); } } checkValid(); } void PromoEditor::checkValid() { bool validAmount = ui->spinboxDiscount->value() > 0.0 ? true : false; bool validDate = ((getDateStart() < getDateEnd()) && (getDateEnd() > QDate::currentDate())) ? true : false; bool valid = isProductSelected() && validAmount && validDate; qDebug()<<"Valid Amount:"<<validAmount<<" Valid Date:"<<validDate<<" finally is valid="<<valid; enableButtonOk(valid); } bool PromoEditor::isProductSelected() { QModelIndex index = ui->productsList->currentIndex(); if (index.isValid()) return true; else return false; } void PromoEditor::setFilter() { QRegExp regexp = QRegExp(ui->editName->text()); if (ui->chByName->isChecked()) { //1st if: Filter by DESC. if (!regexp.isValid() || ui->editName->text().isEmpty() || (ui->editName->text()=="*") ) model->setFilter(""); else model->setFilter(QString("products.name REGEXP '%1'").arg(ui->editName->text())); } else { // filter by category... int catId=-1; QString catText = ui->comboCategory->currentText(); Azahar *myDb = new Azahar; myDb->setDatabase(db); catId = myDb->getCategoryId(catText); //qDebug()<<"Category:"<<catText<<" Id:"<<catId; model->setFilter(QString("products.category=%1").arg(catId)); } } void PromoEditor::setupModel() { if (db.isOpen()) { model->setTable("products"); ui->productsList->setModel(model); ui->productsList->setEditTriggers(QAbstractItemView::NoEditTriggers); ui->productsList->setModelColumn(model->fieldIndex("name")); ui->productsList->setSelectionMode(QAbstractItemView::SingleSelection); model->setFilter(""); model->select(); } } #include "promoeditor.moc"
7,087
C++
.cpp
169
38.727811
118
0.648409
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
752,826
usereditor.cpp
hiramvillarreal_iotpos/iotstock/src/usereditor.cpp
/*************************************************************************** * Copyright (C) 2013-2015 by Hiram R. Villarreal * * hiramvillarreal.ap@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include <KLocale> #include <KMessageBox> #include <KFileDialog> #include <QByteArray> #include "usereditor.h" #include "../../src/enums.h" UserEditorUI::UserEditorUI( QWidget *parent ) : QFrame( parent ) { setupUi( this ); } UserEditor::UserEditor( QWidget *parent ) : KDialog( parent ) { ui = new UserEditorUI( this ); setMainWidget( ui ); setCaption( i18n("User Editor") ); setButtons( KDialog::Ok|KDialog::Cancel ); connect( ui->btnChangeUserPhoto , SIGNAL( clicked() ), this, SLOT( changePhoto() ) ); connect( ui->editUsersUsername, SIGNAL(textEdited(const QString &)),this, SLOT(checkName()) ); QTimer::singleShot(750, this, SLOT(checkName())); } UserEditor::~UserEditor() { delete ui; } void UserEditor::changePhoto() { QString fname = KFileDialog::getOpenFileName(); if (!fname.isEmpty()) { QPixmap p = QPixmap(fname); setPhoto(p); } } void UserEditor::checkName() { if (ui->editUsersUsername->text().isEmpty()) enableButtonOk(false); else enableButtonOk(true); } void UserEditor::setUserName(QString uname) { if (uname == "admin") ui->editUsersUsername->setReadOnly(true); ui->editUsersUsername->setText(uname); } void UserEditor::setUserRole(const int &role) { switch (role) { case roleBasic: ui->chRoleBasic->setChecked(true); break; case roleAdmin: ui->chRoleAdmin->setChecked(true); break; case roleSupervisor: ui->chRoleSupervisor->setChecked(true); break; default: ui->chRoleBasic->setChecked(true); enableButtonOk(true); //for example when old db with user role=0 then we set as basic role, this change must be saved. } } int UserEditor::getUserRole() { if ( ui->chRoleBasic->isChecked() ) return roleBasic; else if (ui->chRoleSupervisor->isChecked()) return roleSupervisor; else return roleAdmin; } void UserEditor::disallowAdminChange(const bool &yes) { //A supervisor cannot change administrator's information/password. if (getUserRole() == roleAdmin) { ui->editUsersPassword->setDisabled(yes); ui->setDisabled(yes); //everything } } #include "usereditor.moc"
3,628
C++
.cpp
98
33.94898
124
0.588386
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
752,827
main.cpp
hiramvillarreal_iotpos/iotstock/src/main.cpp
/*************************************************************************** * Copyright (C) 2013-2015 by Hiram R. Villarreal * * hiramvillarreal.ap@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "iotstock.h" #include <kapplication.h> #include <kaboutdata.h> #include <kcmdlineargs.h> #include <klocale.h> static const char description[] = I18N_NOOP("Iotstock your iotpos!"); static const char version[] = "0.9.6.0 | March 04, 2013"; int main(int argc, char **argv) { KAboutData about("iotstock", 0, ki18n("IotStock"), version, ki18n(description), KAboutData::License_GPL, ki18n("(C) 2007-2011 Miguel Chavez Gamboa"), KLocalizedString(), 0, "miguel@iotpospos.org"); about.addAuthor( ki18n("Miguel Chavez Gamboa"), KLocalizedString(), "miguel@iotpospos.org" ); about.setBugAddress("bugs.iotstock@iotpospos.org"); KCmdLineArgs::init(argc, argv, &about); about.addCredit(ki18n("Roberto Aceves"), ki18n("Many ideas and general help")); about.addCredit(ki18n("Biel Frontera"), ki18n("Code contributor")); about.addCredit(ki18n("Vitali Kari"), ki18n("Code contributor")); about.addCredit(ki18n("Jose Nivar"), ki18n("Many ideas, bug reports and testing")); about.addCredit(ki18n("Benjamin Burt"), ki18n("Many ideas, Documentation Writer, How-to Videos Creation, and general help and support")); KCmdLineOptions options; options.add("+[URL]", ki18n( "Document to open" )); KCmdLineArgs::addCmdLineOptions(options); KApplication app; // register ourselves as a dcop client //app.dcopClient()->registerAs(app.name(), false); // see if we are starting with session management if (app.isSessionRestored()) RESTORE(iotstock) else { // no session.. just start up normally KCmdLineArgs *args = KCmdLineArgs::parsedArgs(); if (args->count() == 0) { iotstock *widget = new iotstock; widget->show(); } else { int i = 0; for (; i < args->count(); i++) { iotstock *widget = new iotstock; widget->show(); } } args->clear(); } return app.exec(); }
3,485
C++
.cpp
69
45.130435
201
0.547885
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
752,828
offersdelegate.cpp
hiramvillarreal_iotpos/iotstock/src/offersdelegate.cpp
/*************************************************************************** * Copyright (C) 2007-2007-2009 by Miguel Chavez Gamboa * * hiramvillarreal.ap@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #define QT_GUI_LIB #include <QtGui> #include <QDate> #include <QSqlRelationalDelegate> #include "offersdelegate.h" OffersDelegate::OffersDelegate(QObject *parent) : QSqlRelationalDelegate(parent) { } void OffersDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { QStyleOptionViewItemV3 opt = option; if (index.column() == 1) { //Alineamos al centro el descuento... opt.displayAlignment = Qt::AlignCenter; //modificamos las opciones... de alieado. const QAbstractItemModel *model = index.model(); QPalette::ColorGroup cg = opt.state & QStyle::State_Enabled ? QPalette::Normal : QPalette::Disabled; if (opt.state & QStyle::State_Selected) painter->fillRect(opt.rect, opt.palette.color(cg, QPalette::Highlight)); double amount = model->data(index, Qt::DisplayRole).toDouble(); int boxH = opt.rect.height() -10; int boxW = opt.rect.width() -5; int boxX = opt.rect.x(); int boxY = opt.rect.y(); int apintar = amount*(boxW/100); //porcentaje del cuadro a pintar que le corresponde al descuento. painter->setBrush(Qt::lightGray); painter->setPen(Qt::darkGray); painter->drawRect(boxX+15,boxY+5,apintar,boxH); if (opt.state & QStyle::State_Selected) painter->setPen(Qt::white); else painter->setPen(Qt::black); painter->setFont(QFont("Times", 9, QFont::Bold)); painter->drawText(boxX-8+boxW/2,boxY+19,QString("%1 %").arg(amount)); } else QSqlRelationalDelegate::paint(painter, opt, index); } QWidget *OffersDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const { if (index.column() == 4 ) return QSqlRelationalDelegate::createEditor(parent, option, index); else { QWidget *editor = NULL; QDoubleSpinBox *dSpinbox = new QDoubleSpinBox(parent); QDateEdit *dateEdit = new QDateEdit(parent); switch(index.column()) { case 1: //discount editor = dSpinbox; dSpinbox->setMinimum(0); dSpinbox->setMaximum(99.99); dSpinbox->setSuffix(" %"); break; case 2: //date editor = dateEdit; break; case 3: //date editor = dateEdit; break; default : //Never must be here... break; } return editor; } } #include "offersdelegate.moc"
3,814
C++
.cpp
80
43.625
122
0.585032
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
752,829
providerseditor.cpp
hiramvillarreal_iotpos/iotstock/src/providerseditor.cpp
/************************************************************************** * Copyright © 2007-2011 by Miguel Chavez Gamboa * * miguel@lemonpos.org * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include <KLocale> #include <KMessageBox> #include <KFileDialog> #include <KStandardDirs> #include <QByteArray> #include <QRegExpValidator> #include <QRegExp> #include <QtSql> #include "providerseditor.h" #include "../../dataAccess/azahar.h" #include "../../src/inputdialog.h" #include "../../mibitWidgets/mibittip.h" #include "../../mibitWidgets/mibitfloatpanel.h" #include "../../src/misc.h" ProvidersEditorUI::ProvidersEditorUI( QWidget *parent ) : QFrame( parent ) { setupUi( this ); } ProvidersEditor::ProvidersEditor( QWidget *parent, bool newProvider, const QSqlDatabase& database ) : KDialog( parent ) { modelCreated = false; db = database; enableButtonOk(false); ui = new ProvidersEditorUI( this ); setMainWidget( ui ); setCaption( i18n("Product Editor") ); setButtons( KDialog::Ok|KDialog::Cancel ); connect( ui->btnRemove, SIGNAL(clicked()), SLOT( removeItem()) ); connect( ui->btnAttach, SIGNAL(clicked()), SLOT( addItem()) ); connect( ui->editName, SIGNAL(editingFinished()), this, SLOT(checkFieldsState())); connect( ui->editAddress, SIGNAL(textChanged()), this, SLOT(checkFieldsState())); connect( ui->editPhone, SIGNAL(editingFinished()), this, SLOT(checkFieldsState())); connect( ui->editCell, SIGNAL(textChanged(const QString &)), this, SLOT(checkFieldsState())); QString path = KStandardDirs::locate("appdata", "styles/"); path = path+"floating_bottom.svg"; panel = new MibitFloatPanel(this, path, Bottom); panel->setSize(350,200); panel->setMode(pmManual); panel->setHiddenTotally(true); panel->addWidget(ui->attachment); connect( ui->btnAdd, SIGNAL(clicked()), panel, SLOT( showPanel() ) ); connect( ui->btnAttach, SIGNAL(clicked()), panel, SLOT( hidePanel() ) ); connect( ui->btnCancelAttach, SIGNAL(clicked()), panel, SLOT( hidePanel()) ); m_pInfo.id = 0; m_pInfo.name = ""; m_pInfo.address = ""; m_pInfo.phone = ""; m_pInfo.cell = ""; } ProvidersEditor::~ProvidersEditor() { //remove products filter m_model->setFilter(""); m_model->select(); m_model2->setFilter(""); m_model2->select(); delete m_model; delete m_model2; delete ui; } void ProvidersEditor::setDb(QSqlDatabase database) { db = database; if (!db.isOpen()) db.open(); setupModel(); } void ProvidersEditor::checkFieldsState() { bool ready = false; if ( !ui->editName->text().isEmpty() && !ui->editAddress->toPlainText().isEmpty() && !ui->editPhone->text().isEmpty() && !ui->editCell->text().isEmpty() ) { ready = true; } enableButtonOk(ready); if (!ready) { //ui->editName->setFocus(); } } void ProvidersEditor::slotButtonClicked(int button) { //update all information... m_pInfo.name = ui->editName->text(); m_pInfo.address = ui->editAddress->toPlainText(); m_pInfo.phone = ui->editPhone->text(); m_pInfo.cell = ui->editCell->text(); if (button == KDialog::Ok) QDialog::accept(); else QDialog::reject(); } void ProvidersEditor::setupModel() { if (!modelCreated) { m_model = new QSqlRelationalTableModel(); m_model2 = new QSqlRelationalTableModel(); modelCreated = true; } m_model->setTable("products_providers"); int pprovIdIndex = m_model->fieldIndex("id"); int pprovProdIdIndex = m_model->fieldIndex("product_id"); int pprovProvIdIndex = m_model->fieldIndex("provider_id"); int pprovPriceIndex= m_model->fieldIndex("price"); m_model->setHeaderData(pprovProdIdIndex, Qt::Horizontal, i18n("Product Name")); m_model->setHeaderData(pprovPriceIndex, Qt::Horizontal, i18n("Last Price")); m_model->setRelation(pprovProdIdIndex, QSqlRelation("products", "code", "name")); ui->prodTable->setModel(m_model); ui->prodTable->setSelectionMode(QAbstractItemView::SingleSelection); ui->prodTable->setColumnHidden(pprovIdIndex, true); ui->prodTable->setColumnHidden(pprovProvIdIndex, true); ui->prodTable->setEditTriggers(QAbstractItemView::NoEditTriggers); ui->prodTable->setCurrentIndex(m_model->index(0, 0)); m_model->select(); ui->prodTable->resizeColumnsToContents(); //set filter according to the provider m_model->setFilter(QString("provider_id=%1").arg(m_pInfo.id)); m_model->select(); //Setup Products model... m_model2->setTable("products"); ui->productsList->setModel(m_model2); ui->productsList->setModelColumn(1); //name ui->productsList->setEditTriggers(QAbstractItemView::NoEditTriggers); m_model2->setFilter(""); m_model2->select(); } void ProvidersEditor::addItem() { Azahar *myDb = new Azahar; myDb->setDatabase(db); //get selected items from list QItemSelectionModel *selectionModel = ui->productsList->selectionModel(); QModelIndexList indexList = selectionModel->selectedRows(); // pasar el indice que quiera (0=code, 1=name) foreach(QModelIndex index, indexList) { qulonglong code = index.data().toULongLong(); // product CODE ProductInfo pInfo; //get product info from db pInfo = myDb->getProductInfo(QString::number(code)); //check if the product to be added is not already there if (!myDb->providerHasProduct(m_pInfo.id, code)) { qDebug()<<"The product "<<code<<" is not provided by the porvider yet"; //insert into the db. ProductProviderInfo info; info.prodId = code; info.provId = m_pInfo.id; info.price = pInfo.price; myDb->addProductToProvider(info); } } m_model->select(); enableButtonOk(true); delete myDb; } void ProvidersEditor::removeItem() { QModelIndex index = ui->prodTable->currentIndex(); if (index != m_model->index(-1,-1)) { //get selected item from table qulonglong pID = m_model->record(index.row()).value("id").toULongLong(); Azahar *myDb = new Azahar; myDb->setDatabase(db); myDb->deleteProductProvider(pID); m_model->select(); delete myDb; enableButtonOk(true); } //there is something selected } void ProvidersEditor::setProviderId(qulonglong id) { //get Info... Azahar *myDb = new Azahar; myDb->setDatabase(db); m_pInfo = myDb->getProviderInfo(id); //update form ui->editName->setText(m_pInfo.name); ui->editAddress->setText(m_pInfo.address); ui->editPhone->setText(m_pInfo.phone); ui->editCell->setText(m_pInfo.cell); //re filter products m_model->setFilter(QString("provider_id=%1").arg(m_pInfo.id)); m_model->select(); } #include "providerseditor.moc"
7,935
C++
.cpp
204
35.52451
108
0.646262
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
752,830
purchaseeditor.cpp
hiramvillarreal_iotpos/iotstock/src/purchaseeditor.cpp
/************************************************************************** * Copyright © 2013-2015 by Hiram R. Villarreal * * hiramvillarreal.ap@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include <KLocale> #include <KMessageBox> #include <KFileDialog> #include <kiconloader.h> #include <kstandarddirs.h> #include <QByteArray> #include <QRegExpValidator> #include "../../dataAccess/azahar.h" #include "../../mibitWidgets/mibittip.h" #include "purchaseeditor.h" #include "subcategoryeditor.h" PurchaseEditorUI::PurchaseEditorUI( QWidget *parent ) : QFrame( parent ) { setupUi( this ); } PurchaseEditor::PurchaseEditor( QWidget *parent ) : KDialog( parent ) { ui = new PurchaseEditorUI( this ); setMainWidget( ui ); setCaption( i18n("Purchase") ); setButtons( KDialog::Ok|KDialog::Cancel ); setDefaultButton(KDialog::None); ui->btnAddItem->setDefault(true); //This makes this button default action when pressing enter on any field. As the setDefaultButton is set to None. //Set Validators for input boxes //QRegExp regexpC("[0-9]{1,13}"); //(EAN-13 y EAN-8) .. y productos sin codigo de barras? //QRegExpValidator * validatorEAN13 = new QRegExpValidator(regexpC, this); //PATCHED on June 6, 2011. To support alphacodes here also. QRegExp regexpC("[0-9]*[A-Za-z_0-9\\\\/\\-]{0,30}"); // Instead of {0,13} fro EAN13, open for up to 30 chars. QRegExpValidator * validatorEAN13 = new QRegExpValidator(regexpC, this); ui->editCode->setValidator(validatorEAN13); ui->editTax->setValidator(new QDoubleValidator(0.00, 999999999999.99, 3,ui->editTax)); ui->editExtraTaxes->setValidator(new QDoubleValidator(0.00, 999999999999.99, 3,ui->editExtraTaxes)); ui->editCost->setValidator(new QDoubleValidator(0.00, 999999999999.99, 3, ui->editCost)); ui->editPoints->setValidator(new QIntValidator(0,999999999, ui->editPoints)); ui->editFinalPrice->setValidator(new QDoubleValidator(0.00,999999999999.99, 3, ui->editFinalPrice)); ui->editItemsPerBox->setValidator(new QDoubleValidator(0.00,999999999999.99, 2, ui->editItemsPerBox)); ui->editPricePerBox->setValidator(new QDoubleValidator(0.00,999999999999.99, 2, ui->editPricePerBox)); ui->editQty->setValidator(new QDoubleValidator(-99999.00,999999999999.99, 2, ui->editQty)); connect( ui->btnPhoto , SIGNAL( clicked() ), this, SLOT( changePhoto() ) ); connect( ui->btnCalculatePrice , SIGNAL( clicked() ), this, SLOT( calculatePrice() ) ); connect( ui->editItemsPerBox , SIGNAL( textEdited(const QString &) ), this, SLOT( calculatePrice() ) ); connect( ui->editPricePerBox , SIGNAL( textEdited(const QString &) ), this, SLOT( calculatePrice() ) ); connect( ui->editCost , SIGNAL( textEdited(const QString &) ), this, SLOT( calculatePrice() ) ); connect( ui->editTax , SIGNAL( textEdited(const QString &) ), this, SLOT( calculatePrice() ) ); connect( ui->editExtraTaxes , SIGNAL( textEdited(const QString &) ), this, SLOT( calculatePrice() ) ); connect( ui->editUtility , SIGNAL( textEdited(const QString &) ), this, SLOT( calculatePrice() ) ); //connect( ui->editCode, SIGNAL(textEdited(const QString &)), SLOT(timerCheck())); for slow type... just keep the "enter" connect( ui->editCode, SIGNAL(returnPressed()), SLOT(checkIfCodeExists())); //connect( ui->editCode, SIGNAL(returnPressed()), ui->editQty, SLOT(setFocus())); connect( ui->btnAddItem, SIGNAL( clicked() ), this, SLOT( addItemToList() ) ); connect(ui->groupBoxedItem, SIGNAL(toggled(bool)), this, SLOT(focusItemsPerBox(bool)) ); connect(ui->btnRemoveItem, SIGNAL( clicked() ), SLOT( deleteSelectedItem() ) ); connect( ui->categoriesCombo, SIGNAL(currentIndexChanged( int )), SLOT(modifyCategory()) ); connect( ui->departmentsCombo, SIGNAL(currentIndexChanged( int )), SLOT(modifyDepartment()) ); connect( ui->btnCreateCategory, SIGNAL(clicked()), SLOT(createNewCategory()) ); connect( ui->btnCreateSubcategory, SIGNAL(clicked()), SLOT(createNewSubcategory()) ); connect( ui->btnCreateDepartment, SIGNAL(clicked()), SLOT(createNewDepartment()) ); connect( ui->btnCreateMeasure, SIGNAL(clicked()), SLOT(createNewMeasure()) ); ui->chIsAGroup->setDisabled(true); QString path = KStandardDirs::locate("appdata", "styles/"); path = path+"tip.svg"; errorPanel = new MibitTip(this, ui->widgetPurchase, path, DesktopIcon("dialog-warning",32) ); lastCode = ""; status = estatusNormal; productExists = false; productsHash.clear(); resetEdits(); totalBuy = 0.0; itemCount = 0.0; totalTaxes = 0.0; QTimer::singleShot(500, this, SLOT(setupTable())); } PurchaseEditor::~PurchaseEditor() { delete ui; } void PurchaseEditor::focusItemsPerBox(bool set) { if (set) { ui->editItemsPerBox->setFocus(); } else ui->editCost->setFocus(); } void PurchaseEditor::setDb(QSqlDatabase database) { db = database; if (!db.isOpen()) db.open(); populateDepartmentsCombo(); //populateCategoriesCombo(); //it is called by populateDepartmentsCombo... populateMeasuresCombo(); } void PurchaseEditor::populateDepartmentsCombo() { Azahar *myDb = new Azahar; myDb->setDatabase(db); ui->departmentsCombo->clear(); ui->departmentsCombo->addItems(myDb->getDepartmentsList()); populateCategoriesCombo(); //call populateCategoriesCombo also! delete myDb; } void PurchaseEditor::populateCategoriesCombo() { QSqlQuery query(db); Azahar *myDb = new Azahar; myDb->setDatabase(db); ui->categoriesCombo->addItems(myDb->getCategoriesList()); populateSubCategoriesCombo(); delete myDb; } void PurchaseEditor::populateSubCategoriesCombo() { QSqlQuery query(db); Azahar *myDb = new Azahar; myDb->setDatabase(db); ui->subcategoriesCombo->clear(); ui->subcategoriesCombo->addItems(myDb->getSubCategoriesList()); delete myDb; } void PurchaseEditor::populateMeasuresCombo() { QSqlQuery query(db); Azahar *myDb = new Azahar; myDb->setDatabase(db); ui->measuresCombo->addItems(myDb->getMeasuresList()); delete myDb; } int PurchaseEditor::getCategoryId() { QSqlQuery query(db); int code=-1; QString currentText = ui->categoriesCombo->currentText(); Azahar *myDb = new Azahar; myDb->setDatabase(db); code = myDb->getCategoryId(currentText); delete myDb; return code; } int PurchaseEditor::getSubCategoryId() { QSqlQuery query(db); int code=-1; QString currentText = ui->subcategoriesCombo->currentText(); Azahar *myDb = new Azahar; myDb->setDatabase(db); code = myDb->getSubCategoryId(currentText); delete myDb; return code; } int PurchaseEditor::getMeasureId() { QSqlQuery query(db); int code=-1; QString currentText = ui->measuresCombo->currentText(); Azahar *myDb = new Azahar; myDb->setDatabase(db); code = myDb->getMeasureId(currentText); delete myDb; return code; } void PurchaseEditor::setDepartment(QString str) { int idx = ui->departmentsCombo->findText(str,Qt::MatchCaseSensitive); if (idx > -1) ui->departmentsCombo->setCurrentIndex(idx); else { qDebug()<<"Department not found:"<<str; } } void PurchaseEditor::setDepartment(int i) { QString text = getDepartmentStr(i); setDepartment(text); qDebug()<<"SET DEPARTMENT INT :: Department Id:"<<i<<" Name:"<<text; } void PurchaseEditor::setCategory(QString str) { int idx = ui->categoriesCombo->findText(str,Qt::MatchCaseSensitive); if (idx > -1) ui->categoriesCombo->setCurrentIndex(idx); else { qDebug()<<"Str not found:"<<str; } } void PurchaseEditor::setCategory(int i) { QString text = getCategoryStr(i); setCategory(text); } void PurchaseEditor::setSubCategory(QString str) { if (str == "") {ui->subcategoriesCombo->setCurrentIndex(0); return;} int idx = ui->subcategoriesCombo->findText(str,Qt::MatchCaseSensitive); if (idx > -1) ui->subcategoriesCombo->setCurrentIndex(idx); else { qDebug()<<"Str not found:"<<str; } } void PurchaseEditor::setSubCategory(int i) { QString text = getSubCategoryStr(i); qDebug()<<" Setting subcateory id "<<i<< ":"<<text; setSubCategory(text); } void PurchaseEditor::setMeasure(int i) { QString text = getMeasureStr(i); setMeasure(text); } void PurchaseEditor::setMeasure(QString str) { int idx = ui->measuresCombo->findText(str,Qt::MatchCaseSensitive); if (idx > -1) ui->measuresCombo->setCurrentIndex(idx); else { qDebug()<<"Str not found:"<<str; } } int PurchaseEditor::getDepartmentId() { int code=-1; QString currentText = ui->departmentsCombo->currentText(); Azahar *myDb = new Azahar; myDb->setDatabase(db); code = myDb->getDepartmentId(currentText); delete myDb; return code; } QString PurchaseEditor::getDepartmentStr(int c) { Azahar *myDb = new Azahar; myDb->setDatabase(db); QString str = myDb->getDepartmentStr(c); delete myDb; return str; } QString PurchaseEditor::getCategoryStr(int c) { Azahar *myDb = new Azahar; myDb->setDatabase(db); QString str = myDb->getCategoryStr(c); delete myDb; return str; } QString PurchaseEditor::getSubCategoryStr(int c) { Azahar *myDb = new Azahar; myDb->setDatabase(db); QString str = myDb->getSubCategoryStr(c); delete myDb; return str; } QString PurchaseEditor::getMeasureStr(int c) { Azahar *myDb = new Azahar; myDb->setDatabase(db); QString str = myDb->getMeasureStr(c); delete myDb; return str; } void PurchaseEditor::changePhoto() { QString fname = KFileDialog::getOpenFileName(); if (!fname.isEmpty()) { QPixmap p = QPixmap(fname); setPhoto(p); } } void PurchaseEditor::calculatePrice() { double finalPrice=0.0; bool costOk,profitOk,taxOk,etaxOk; if (ui->editCost->text().isEmpty() && !ui->groupBoxedItem->isChecked() ) { ui->editCost->setText("0.0"); //ui->editCost->setFocus(); ui->editCost->setStyleSheet("background-color: rgb(255,100,0); color:white; selection-color: white; font-weight:bold;"); costOk = false; } else { ui->editCost->setStyleSheet(""); costOk=true; } if (ui->editUtility->text().isEmpty()) { //ui->editUtility->setFocus(); ui->editUtility->setText("0.0"); ui->editUtility->setStyleSheet("background-color: rgb(255,100,0); color:white; selection-color: white; font-weight:bold;"); profitOk=false; } else { ui->editUtility->setStyleSheet(""); profitOk=true; } if (ui->editTax->text().isEmpty()) { ui->editTax->setText("0.0"); //ui->editTax->setFocus(); ui->editTax->selectAll(); ui->editTax->setStyleSheet("background-color: rgb(255,100,0); color:white; selection-color: white; font-weight:bold;"); taxOk=false; } else { ui->editTax->setStyleSheet(""); taxOk=true; } if (ui->editExtraTaxes->text().isEmpty()) { ui->editExtraTaxes->setText("0.0"); //ui->editExtraTaxes->setFocus(); ui->editExtraTaxes->selectAll(); ui->editExtraTaxes->setStyleSheet("background-color: rgb(255,100,0); color:white; selection-color: white; font-weight:bold;"); etaxOk = false; } else { etaxOk = true; ui->editExtraTaxes->setStyleSheet(""); } //now check which are ZEROs // if (!ui->editExtraTaxes->text().isEmpty() && ui->editExtraTaxes->text().toDouble()<=0) // ui->editExtraTaxes->setStyleSheet("background-color: rgb(255,100,0); color:white; selection-color: white; font-weight:bold;"); // else ui->editExtraTaxes->setStyleSheet(""); if (!ui->editTax->text().isEmpty() && ui->editTax->text().toDouble()<=0) ui->editTax->setStyleSheet("background-color: rgb(255,100,0); color:white; selection-color: white; font-weight:bold;"); else ui->editTax->setStyleSheet(""); if (!ui->editUtility->text().isEmpty() && ui->editUtility->text().toDouble()<=0) ui->editUtility->setStyleSheet("background-color: rgb(255,100,0); color:white; selection-color: white; font-weight:bold;"); else ui->editUtility->setStyleSheet(""); if (!ui->editCost->text().isEmpty() && ui->editCost->text().toDouble()<=0) ui->editCost->setStyleSheet("background-color: rgb(255,100,0); color:white; selection-color: white; font-weight:bold;"); else ui->editCost->setStyleSheet(""); if (costOk && profitOk && taxOk && etaxOk ) { //TODO: if TAXes are included in cost... double cWOTax = 0; double tax = ui->editTax->text().toDouble(); double tax2 = ui->editExtraTaxes->text().toDouble(); double utility = ui->editUtility->text().toDouble(); Azahar *myDb = new Azahar; myDb->setDatabase(db); // We assume that tax rules for prices also apply to costs. if (myDb->getConfigTaxIsIncludedInPrice()) cWOTax= (ui->editCost->text().toDouble())/(1+((tax+tax2)/100)); else cWOTax = ui->editCost->text().toDouble(); double cost = cWOTax; utility = ((utility/100)*cost); double cu=cost+utility; //We need the tax recalculated from the costs+utility, this time taxes are expressed in $ tax = ((tax/100)*(cost)); ///NOTE fixed:when paying for a product we pay taxes for the cost not the cost+profit tax2 = ((tax2/100)*(cost)); if (ui->groupBoxedItem->isChecked()){ double itemsPerBox = 0; double pricePerBox = 0; if (!ui->editItemsPerBox->text().isEmpty()) itemsPerBox = ui->editItemsPerBox->text().toDouble(); if (!ui->editPricePerBox->text().isEmpty()) pricePerBox = ui->editPricePerBox->text().toDouble(); if (!ui->editItemsPerBox->text().isEmpty() || !ui->editPricePerBox->text().isEmpty()) return; tax = ui->editTax->text().toDouble(); tax2 = ui->editExtraTaxes->text().toDouble(); if (myDb->getConfigTaxIsIncludedInPrice()) cWOTax= (pricePerBox/itemsPerBox)/(1+((tax+tax2)/100)); else cWOTax = pricePerBox/itemsPerBox; cost = cWOTax; ui->editCost->setText(QString::number(cost)); utility = ((ui->editUtility->text().toDouble()/100)*cost); cu = cost + utility; tax = ((tax/100)*(cost));///NOTE fixed:when paying for a product we pay taxes for the cost not the cost+profit tax2 = ((tax2/100)*(cost)); finalPrice = cu + tax + tax2; } else finalPrice = cost + utility + tax + tax2; qDebug()<<"cWOTax ="<<cWOTax<<" tax1="<<tax<<" tax2="<<tax2<<" FinalPrice:"<<finalPrice; ui->editFinalPrice->setText(QString::number(finalPrice)); ui->editFinalPrice->selectAll(); delete myDb; } } void PurchaseEditor::timerCheck() { if (ui->editCode->text() == lastCode) { //ok no changes. get this product checkIfCodeExists(); } else { lastCode = ui->editCode->text(); QTimer::singleShot(2000, this, SLOT(justCheck())); } } void PurchaseEditor::justCheck() { if (ui->editCode->text() == lastCode) { //ok no changes one second ago in code. get this product checkIfCodeExists(); } } //This will check for codes and vendor codes. void PurchaseEditor::checkIfCodeExists() { Azahar *myDb = new Azahar; myDb->setDatabase(db); gelem = ""; QString codeStr = ui->editCode->text(); if (codeStr.isEmpty()) codeStr = "0"; qulonglong cVc = 0; cVc = myDb->getProductCodeFromVendorcode(codeStr); ProductInfo pInfo; //NOTE: this may have a failure chance, if vendor code is exactly the same as some product code (numbers) then it will be a false positive. if (cVc > 0) { //use the vendor code instead. pInfo = myDb->getProductInfo(QString::number(cVc)); ui->editCode->setText(QString::number(cVc));//for adding to work. } else { //use the product code... pInfo = myDb->getProductInfo(codeStr); } if (pInfo.code ==0 && pInfo.desc=="Ninguno") productExists = false; if (pInfo.code > 0) { status = estatusMod; productExists = true; qtyOnDb = pInfo.stockqty; qDebug()<<"Product code:"<<pInfo.code<<" Product AlphaCode:"<<pInfo.alphaCode<<" qtyOnDb:"<<qtyOnDb<<" SubCat:"<<pInfo.subcategory; //Prepopulate dialog... ui->editDesc->setText(pInfo.desc); setDepartment(pInfo.department); setCategory(pInfo.category); setSubCategory(pInfo.subcategory); setMeasure(pInfo.units); ui->editCost->setText(QString::number(pInfo.cost)); ui->editTax->setText(QString::number(pInfo.tax)); ui->editExtraTaxes->setText(QString::number(pInfo.extratax)); ui->editFinalPrice->setText(QString::number(pInfo.price)); ui->editPoints->setText(QString::number(pInfo.points)); ui->chIsAGroup->setChecked(pInfo.isAGroup); ui->editAlphacode->setText(pInfo.alphaCode); ui->editVendorcode->setText(pInfo.vendorCode); gelem = pInfo.groupElementsStr; if (!(pInfo.photo).isEmpty()) { QPixmap photo; photo.loadFromData(pInfo.photo); setPhoto(photo); } } else { qDebug()<< "no product found with code "<<codeStr; qulonglong codeSaved = getCode(); QString codeStr = getCodeStr(); resetEdits(); if (codeSaved > 0) //do not set code "0" in the input box, just let it empty, setCode(codeSaved); else { if (!codeStr.isEmpty()) setCode(codeStr); } } ui->editQty->setFocus(); //always focus the Qty input box. qDebug()<<"SET QTY FOCUS"; delete myDb; } void PurchaseEditor::slotButtonClicked(int button) { if (button == KDialog::Ok && productsHash.count() > 0) { //allowing negative numbers to return items to providers. itemCount != 0 && //NOTE: the only problem is when decrementing more than the stock, which will end with 0, not negative stock. if (status == estatusNormal) QDialog::accept(); else { qDebug()<< "Button = OK, status == statusMOD"; done(estatusMod); } } else { if (button == KDialog::Cancel ) { QDialog::reject(); } } } void PurchaseEditor::setupTable() { QSize tableSize = ui->tableView->size(); ui->tableView->horizontalHeader()->resizeSection(0, (tableSize.width()/7)); ui->tableView->horizontalHeader()->resizeSection(1, (tableSize.width()/7)*3); ui->tableView->horizontalHeader()->resizeSection(2,(tableSize.width()/7)*1.4); ui->tableView->horizontalHeader()->resizeSection(3,(tableSize.width()/7)*1.4); } void PurchaseEditor::addItemToList() { qDebug()<<"Adding item to list..."; ProductInfo pInfo; Azahar *myDb = new Azahar; myDb->setDatabase(db); bool ok=false; if (ui->editCode->text().isEmpty()) ui->editCode->setFocus(); else if (ui->editQty->text().isEmpty() || ui->editQty->text()=="0") ui->editQty->setFocus(); else if (ui->editDesc->text().isEmpty()) ui->editDesc->setFocus(); else if (ui->editPoints->text().isEmpty()) ui->editPoints->setFocus(); else if (ui->editCost->text().isEmpty()) ui->editCost->setFocus(); else if (ui->editTax->text().isEmpty()) ui->editTax->setFocus(); else if (ui->editFinalPrice->text().isEmpty()) ui->editFinalPrice->setFocus(); else if ((ui->editUtility->text().isEmpty() && ui->editFinalPrice->text().isEmpty()) || ui->editFinalPrice->text().toDouble() < ui->editCost->text().toDouble() ) ui->editFinalPrice->setFocus(); else if (ui->groupBoxedItem->isChecked() && (ui->editItemsPerBox->text().isEmpty() || ui->editItemsPerBox->text()=="0")) ui->editItemsPerBox->setFocus(); else if (ui->groupBoxedItem->isChecked() && (ui->editPricePerBox->text().isEmpty() || ui->editPricePerBox->text()=="0")) ui->editPricePerBox->setFocus(); else ok = true; if (ok) { ProductInfo info = myDb->getProductInfo( getCodeStr() ); //if is an Unlimited stock product, do not allow to add to the purchase. if (info.hasUnlimitedStock) { errorPanel->showTip(i18n("<b>Unlimited Stock Products cannot be purchased.</b>"), 10000); return; } //FIX BUG: dont allow enter new products.. dont know why? new code on 'continue' statement. if (info.code == 0) { //new product info.code = getCode(); info.stockqty = 0; //new product info.lastProviderId=1; //for now.. fixme in the future } //update p.info from the dialog info.desc = getDescription(); info.price = getPrice(); info.cost = getCost(); info.tax = getTax1(); info.extratax= getTax2(); info.photo = getPhotoBA(); info.units = getMeasureId(); info.department = getDepartmentId(); info.category= getCategoryId(); info.subcategory= getSubCategoryId(); info.utility = getProfit(); info.points = getPoints(); info.purchaseQty = getPurchaseQty(); info.validDiscount = productExists; //used to check if product is already on db. info.alphaCode = getAlphacode(); info.vendorCode = getVendorcode(); if (info.isAGroup) { // get each product fo the group/pack QStringList list = gelem.split(","); for (int i=0; i<list.count(); ++i) { QStringList tmp = list.at(i).split("/"); if (tmp.count() == 2) { //ok 2 fields qulonglong code = tmp.at(0).toULongLong(); pInfo = myDb->getProductInfo(QString::number(code)); pInfo.purchaseQty = getPurchaseQty(); pInfo.validDiscount = true; // all grouped products exists insertProduct(pInfo); ///inserting each product of the group } // correct fields }//for each element } else insertProduct(info); //resetEdits(); ui->editCode->setFocus(); } delete myDb; } void PurchaseEditor::insertProduct(ProductInfo info) { //When a product is already on list, increment qty. bool existed = false; if (info.code>0) { if (productsHash.contains(info.code)) { info = productsHash.take(info.code); //re get it from hash double finalStock = info.purchaseQty + info.stockqty; double suggested; if (-info.stockqty == 0) suggested = 1; else suggested = -info.stockqty; qDebug()<<"Purchase Qty:"<<info.purchaseQty<<" product stock:"<<info.stockqty<<" final Stock:"<<finalStock; if (finalStock < 0) { qDebug()<<"Negative stock!, suggested purchase:"<<suggested; //launch a message errorPanel->showTip(i18n("<b>Stock is negative.</b> The <i>minimum</i> suggested purchase is <b>%1</b>", suggested), 10000); //setPurchaseQty(suggested); } info.purchaseQty += getPurchaseQty(); itemCount += getPurchaseQty(); totalBuy = totalBuy + info.cost*getPurchaseQty(); existed = true; } else { double finalStock = info.purchaseQty + info.stockqty; double suggested; if (-info.stockqty == 0) suggested = 1; else suggested = -info.stockqty; qDebug()<<"Purchase Qty:"<<info.purchaseQty<<" product stock:"<<info.stockqty<<" final Stock:"<<finalStock; if (finalStock < 0) { qDebug()<<"Negative stock!, suggested purchase:"<<suggested; //launch a message errorPanel->showTip(i18n("<b>Stock is negative.</b> The <i>minimum</i> suggested purchase is <b>%1</b>", suggested), 10000); //setPurchaseQty(suggested); } itemCount += info.purchaseQty; totalBuy = totalBuy + info.cost*info.purchaseQty; qDebug()<<"NEW DEP:"<<info.department<<" New CAT:"<<info.category<<" NEW SUBCAT:"<<info.subcategory; } //its ok to reset edits now... resetEdits(); //calculate taxes for this item. Calculated from the costs. Azahar *myDb = new Azahar; myDb->setDatabase(db); double cWOTax = 0; if (myDb->getConfigTaxIsIncludedInPrice()) cWOTax= (info.cost)/(1+((info.tax+info.extratax)/100)); else cWOTax = info.cost; double tax = cWOTax*info.purchaseQty*(info.tax/100); double tax2= cWOTax*info.purchaseQty*(info.extratax/100); totalTaxes += tax + tax2; // add this product taxes to the total taxes in the purchase. qDebug()<<"Total taxes updated:"<<totalTaxes<<" Taxes for this product:"<<tax+tax2; delete myDb; double finalCount = info.purchaseQty + info.stockqty; info.groupElementsStr=""; //grouped products cannot be a group. //insert item to productsHash productsHash.insert(info.code, info); //insert item to ListView if (!existed) { int rowCount = ui->tableView->rowCount(); ui->tableView->insertRow(rowCount); ui->tableView->setItem(rowCount, 0, new QTableWidgetItem(QString::number(info.code))); ui->tableView->setItem(rowCount, 1, new QTableWidgetItem(info.desc)); ui->tableView->setItem(rowCount, 2, new QTableWidgetItem(QString::number(info.purchaseQty))); ui->tableView->setItem(rowCount, 3, new QTableWidgetItem(QString::number(finalCount))); } else { //simply update the groupView with the new qty for (int ri=0; ri<ui->tableView->rowCount(); ++ri) { QTableWidgetItem * item = ui->tableView->item(ri, 1); QString name = item->data(Qt::DisplayRole).toString(); if (name == info.desc) { //update QTableWidgetItem *itemQ = ui->tableView->item(ri, 2); itemQ->setData(Qt::EditRole, QVariant(QString::number(info.purchaseQty))); itemQ = ui->tableView->item(ri, 3); itemQ->setData(Qt::EditRole, QVariant(QString::number(finalCount))); continue; //HEY PURIST, WHEN I GOT SOME TIME I WILL CLEAN IT } } } ui->tableView->horizontalHeader()->setResizeMode(QHeaderView::Interactive); ui->tableView->resizeRowsToContents(); //totalBuy = totalBuy + info.cost*info.purchaseQty; //itemCount = itemCount + info.purchaseQty; //update info on group caption ui->groupBox->setTitle( i18n("Items in this purchase [ %1 items, %2 ]",itemCount, KGlobal::locale()->formatMoney(totalBuy, QString(), 2) ) ); qDebug()<<"totalBuy until now:"<<totalBuy<<" itemCount:"<<itemCount<<"info.cost:"<<info.cost<<"info.purchaseQty:"<<info.purchaseQty; } else qDebug()<<"Item "<<info.code<<" already on hash"; } void PurchaseEditor::deleteSelectedItem() //added on dec 3, 2009 { if (ui->tableView->currentRow()!=-1) { int row = ui->tableView->currentRow(); QTableWidgetItem *item = ui->tableView->item(row, colCode); qulonglong code = item->data(Qt::DisplayRole).toULongLong(); if (productsHash.contains(code)) { //delete it from hash and from view ProductInfo info = productsHash.take(code); ui->tableView->removeRow(row); //update qty and $ of the purchase totalBuy -= (info.cost*info.purchaseQty); itemCount -= info.purchaseQty; //calculate taxes for this item. Calculated from the costs. Azahar *myDb = new Azahar; myDb->setDatabase(db); double cWOTax = 0; if (myDb->getConfigTaxIsIncludedInPrice()) cWOTax= (info.cost)/(1+((info.tax+info.extratax)/100)); else cWOTax = info.cost; double tax = cWOTax*info.purchaseQty*(info.tax/100); double tax2= cWOTax*info.purchaseQty*(info.extratax/100); totalTaxes = totalTaxes - tax - tax2; qDebug()<<"Total taxes updated:"<<totalTaxes; delete myDb; ui->groupBox->setTitle( i18n("Items in this purchase [ %1 items, %2 ]",itemCount, KGlobal::locale()->formatMoney(totalBuy, QString(), 2) ) ); } } } void PurchaseEditor::resetEdits() { ui->editCode->setText(""); ui->editDesc->setText(""); ui->editCost->setText(""); ui->editTax->setText(""); ui->editExtraTaxes->setText("0.0"); ui->editFinalPrice->setText(""); ui->editUtility->setText(""); qtyOnDb = 0; pix = QPixmap(0,0); //null pixmap. ui->labelPhoto->setText(i18n("No Photo")); ui->editPoints->setText("0"); ui->editItemsPerBox->setText(""); ui->editPricePerBox->setText(""); ui->editQty->setText(""); ui->chIsAGroup->setChecked(false); ui->editAlphacode->setText(""); ui->editVendorcode->setText(""); setSubCategory(0); setDepartment(0); setCategory(0); gelem = ""; } double PurchaseEditor::getPurchaseQty() { if (ui->groupBoxedItem->isChecked()) { if ( ui->editItemsPerBox->text().isEmpty() ) return ui->editQty->text().toDouble(); else return (ui->editQty->text().toDouble())*(ui->editItemsPerBox->text().toDouble()); } else return ui->editQty->text().toDouble(); } void PurchaseEditor::setIsAGroup(bool value) { ui->chIsAGroup->setChecked(value); } void PurchaseEditor::modifyDepartment() { //When a department is changed, we must filter categories according. QString depText = ui->departmentsCombo->currentText(); Azahar *myDb = new Azahar; myDb->setDatabase(db); //get categories.. qulonglong parentId = myDb->getDepartmentId( depText ); QStringList catList = myDb->getCategoriesList( parentId ); ui->categoriesCombo->clear(); ui->categoriesCombo->addItems( catList ); qDebug()<<"CAT LIST for "<<depText<<" :"<<catList; delete myDb; } void PurchaseEditor::modifyCategory() { //When a category is changed, we must filter subcategories according. QString catText = ui->categoriesCombo->currentText(); Azahar *myDb = new Azahar; myDb->setDatabase(db); //get subcategories' children qulonglong parentId = myDb->getCategoryId( catText ); QStringList subcatList = myDb->getSubCategoriesList( parentId ); ui->subcategoriesCombo->clear(); ui->subcategoriesCombo->addItems( subcatList ); qDebug()<<"SUBCAT LIST for ("<<parentId<<") "<<catText<<" :"<<subcatList; delete myDb; } void PurchaseEditor::createNewSubcategory() { bool ok=false; QString cat = QInputDialog::getText(this, i18n("New subcategory"), i18n("Enter the new subcategory:"), QLineEdit::Normal, "", &ok ); if (ok && !cat.isEmpty()) { Azahar *myDb = new Azahar; myDb->setDatabase(db); if (!myDb->insertSubCategory(cat)) qDebug()<<"Error:"<<myDb->lastError(); //modifyCategory(); //BUG:It is weird that this does not appends the new item; it should do it. ui->subcategoriesCombo->addItems( QStringList(cat) ); //WORK AROUND setSubCategory(cat); //NOTE: Hey, the subcategory here belongs to a category.. so we must insert the m2m relation! qulonglong scId = myDb->getSubCategoryId(cat); qulonglong cId = myDb->getCategoryId( ui->categoriesCombo->currentText() ); qDebug()<<cId<<"-->"<<scId<<" | "<<cat<<"-->"<<ui->categoriesCombo->currentText(); if (!myDb->insertM2MCategorySubcategory(cId, scId)) qDebug()<<"ERROR:"<<myDb->lastError(); delete myDb; } } void PurchaseEditor::createNewCategory() { //launch dialog to ask for the new child. Using this same dialog. SubcategoryEditor *scEditor = new SubcategoryEditor(this); scEditor->setDb(db); Azahar *myDb = new Azahar; myDb->setDatabase(db); QStringList list = myDb->getSubCategoriesList(); scEditor->setCatList( myDb->getCategoriesList() ); scEditor->setScatList( list ); scEditor->populateList( list ); scEditor->setDialogType(2); //category = 2 scEditor->setLabelForName(i18n("New category:")); scEditor->setLabelForList(i18n("Select the child subcategories for this category:")); if ( scEditor->exec() ) { QString text = scEditor->getName(); QStringList children = scEditor->getChildren(); qDebug()<<text<<" CHILDREN:"<<children; //Create the category if (!myDb->insertCategory(text)) { qDebug()<<"Error:"<<myDb->lastError(); delete myDb; return; } qulonglong cId = myDb->getCategoryId(text); //create the m2m relations for the new category->subcategory. foreach(QString cat, children) { //get subcategory id qulonglong scId = myDb->getSubCategoryId(cat); //create the link [category] --> [subcategory] myDb->insertM2MCategorySubcategory(cId, scId); } //reload categories combo //modifyDepartment();//BUG:It is weird that this does not appends the new item; it should do it. ui->categoriesCombo->addItems( QStringList(text) ); //WORK AROUND setCategory(text); //set the newly created category... } } void PurchaseEditor::createNewDepartment() { //launch dialog to ask for the new child. Using this same dialog. SubcategoryEditor *scEditor = new SubcategoryEditor(this); scEditor->setDb(db); Azahar *myDb = new Azahar; myDb->setDatabase(db); QStringList list = myDb->getCategoriesList(); scEditor->setCatList( list ); scEditor->setScatList( myDb->getSubCategoriesList() ); scEditor->populateList( list ); scEditor->setDialogType(1); //department = 1 scEditor->setLabelForName(i18n("New department:")); scEditor->setLabelForList(i18n("Select the child categories for this department:")); if ( scEditor->exec() ) { QString text = scEditor->getName(); QStringList children = scEditor->getChildren(); qDebug()<<text<<" CHILDREN:"<<children; //Create the department if (!myDb->insertDepartment(text)) { qDebug()<<"Error:"<<myDb->lastError(); delete myDb; return; } qulonglong depId = myDb->getDepartmentId(text); //create the m2m relations for the new department->category. foreach(QString cat, children) { //get category id qulonglong cId = myDb->getCategoryId(cat); //create the link [category] --> [subcategory] myDb->insertM2MDepartmentCategory(depId, cId); } //reload departments combo populateDepartmentsCombo(); //ui->DepartmentsCombo->addItems( QStringList(text) ); //WORK AROUND setDepartment(text); //set the newly created category... } } void PurchaseEditor::createNewMeasure() { bool ok=false; QString meas = QInputDialog::getText(this, i18n("New Weight or Measure"), i18n("Enter the new weight or measure to insert:"), QLineEdit::Normal, "", &ok ); if (ok && !meas.isEmpty()) { Azahar *myDb = new Azahar; if (!db.isOpen()) db.open(); myDb->setDatabase(db); if (!myDb->insertMeasure(meas)) qDebug()<<"Error:"<<myDb->lastError(); populateMeasuresCombo(); setMeasure(meas); delete myDb; } } #include "purchaseeditor.moc"
35,804
C++
.cpp
859
36.558789
195
0.660156
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
752,831
usersdelegate.cpp
hiramvillarreal_iotpos/iotstock/src/usersdelegate.cpp
/*************************************************************************** * Copyright (C) 2013-2015 by Hiram R. Villarreal * * hiramvillarreal.ap@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include <QtGui> #include <QtSql> #include <QMouseEvent> #include <QPaintEvent> #include <klocale.h> #include <kstandarddirs.h> #include <kiconloader.h> #include "usersdelegate.h" void UsersDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { //painting background when selected... //QPalette::ColorGroup cg = option.state & QStyle::State_Enabled // ? QPalette::Normal : QPalette::Disabled; //Painting frame painter->setRenderHint(QPainter::Antialiasing); QString pixName; if (option.state & QStyle::State_Selected) pixName = KStandardDirs::locate("appdata", "images/itemBox_selected_Big.png"); else pixName = KStandardDirs::locate("appdata", "images/itemBox_Big.png"); painter->drawPixmap(option.rect.x()+5,option.rect.y()+5, QPixmap(pixName)); //get item data const QAbstractItemModel *model = index.model(); int row = index.row(); QModelIndex nameIndex = model->index(row, 1); QString name = model->data(nameIndex, Qt::DisplayRole).toString(); QByteArray pixData = model->data(index, Qt::DisplayRole).toByteArray(); //preparing photo to paint it... QPixmap pix; if (!pixData.isEmpty() or !pixData.isNull()) { pix.loadFromData(pixData); } else { //null pixmap, draw a default one... pix = QPixmap(DesktopIcon("iotpos-user", 128)); } //Draw pixmap int max = 128; if ((pix.height() > max) || (pix.width() > max) ) { if (pix.height() == pix.width()) { pix = pix.scaled(QSize(max, max)); } else if (pix.height() > pix.width() ) { pix = pix.scaledToHeight(max); } else { pix = pix.scaledToWidth(max); } } int x = option.rect.x() + (option.rect.width()/2) - (pix.width()/2) -1; int y = option.rect.y() + (option.rect.height()/2) - (pix.height()/2) - 10; //painting photo if (!pix.isNull()) painter->drawPixmap(x,y, pix); //Painting name QFont font = QFont("DroidSans.ttf", 10); font.setBold(true); //getting name size in pixels... QFontMetrics fm(font); int strSize = fm.width(name); int aproxPerChar = fm.width("A"); QString nameToDisplay = name; int boxSize = option.rect.width()-15; //minus margin and frame-lines if (strSize > boxSize) { int excess = strSize-boxSize; int charEx = (excess/aproxPerChar)+2; nameToDisplay = name.left(name.length()-charEx-5) +"..."; } painter->setFont(font); if (option.state & QStyle::State_Selected) { painter->setPen(Qt::yellow); painter->drawText(option.rect.x()+10,option.rect.y()+138, 147,20, Qt::AlignCenter, nameToDisplay); } else { painter->setPen(Qt::white); painter->drawText(option.rect.x()+10,option.rect.y()+138, 147,20, Qt::AlignCenter, nameToDisplay); } } QSize UsersDelegate::sizeHint(const QStyleOptionViewItem &optionUnused, const QModelIndex &indexUnused) const { return QSize(170,170); } #include "usersdelegate.moc"
4,575
C++
.cpp
103
39.495146
105
0.572423
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
752,832
iotstock.cpp
hiramvillarreal_iotpos/iotstock/src/iotstock.cpp
/************************************************************************** * Copyright © 2013-2015 by Hiram R. Villarreal * * hiramvillarreal.ap@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "iotstock.h" #include "iotstockview.h" #include "settings.h" #include <qapplication.h> #include <qpainter.h> #include <QDragEnterEvent> #include <QDropEvent> #include <QPrinter> #include <QTimer> #include <QDesktopWidget> #include <kdeversion.h> #include <kglobal.h> #include <kiconloader.h> #include <kmenubar.h> #include <kstatusbar.h> #include <kconfigdialog.h> //#include <kio/netaccess.h> // #include <kfiledialog.h> #include <kactioncollection.h> #include <kaction.h> #include <KLocale> #include <kled.h> #include <kstandarddirs.h> iotstock::iotstock() //: KXmlGuiWindow(0,Qt::FramelessWindowHint ), : KXmlGuiWindow( ), m_view(new iotstockView(this)), m_printer(0) { setObjectName(QLatin1String("iotstock")); // accept dnd setAcceptDrops(false); // tell the KXmlGuiWindow that this is indeed the main widget setCentralWidget(m_view); // then, setup our actions setupActions(); //Add some widgets to status bar led = new KLed; led->off(); statusBar()->addWidget(led); //FIXME: Que cuando se escriba algo en la barra de status, quede el LED ahi tambien. // add a status bar statusBar()->show(); // Add typical actions and save size/toolbars/statusbar setupGUI(); int y = (QApplication::desktop()->height()); if (y < 640){ setWindowState( windowState() | Qt::WindowFullScreen );// set } else { setWindowState( windowState() | Qt::WindowMaximized); }// set disableUI(); // allow the view to change the statusbar and caption connect(m_view, SIGNAL(signalChangeStatusbar(const QString&)), this, SLOT(changeStatusbar(const QString&))); connect(m_view, SIGNAL(signalChangeCaption(const QString&)), this, SLOT(changeCaption(const QString&))); connect(m_view, SIGNAL(signalDisconnected()), this, SLOT(setDisconnected())); connect(m_view, SIGNAL(signalConnected()), this, SLOT(setConnected())); connect(m_view, SIGNAL(signalShowPrefs()), SLOT(optionsPreferences()) ); connect(m_view, SIGNAL(signalSalir() ), SLOT(salir() )); connect(m_view, SIGNAL(signalShowDbConfig()), this, SLOT(showDBConfigDialog())); connect(m_view, SIGNAL(signalAdminLoggedOn()), this, SLOT(enableUI())); connect(m_view, SIGNAL(signalAdminLoggedOff()), this, SLOT(disableUI())); connect(m_view, SIGNAL(signalSupervisorLoggedOn()), this, SLOT(enableUI())); QTimer::singleShot(500, this, SLOT(hideMenuBar())); timer = new QTimer(this); connect(timer, SIGNAL(timeout()), this, SLOT(fixGeom())); timer->setInterval(5000); //timer->start(); loadStyle(); } iotstock::~iotstock() { delete m_printer; } //NOTE: There is a problem with taskbar panel applets on the desktop (plasma widgets), the 145 pixels is a simple qty that works for me. void iotstock::fixGeom() { //qDebug()<<"Window Size:"<<geometry()<<"desktop size:"<<QApplication::desktop()->screenGeometry(this); if (geometry().height() > (QApplication::desktop()->screenGeometry(this).height()-115)) { QRect geom = geometry(); geom.setHeight(QApplication::desktop()->screenGeometry(this).height()-145); geom.setWidth(QApplication::desktop()->screenGeometry(this).width()-5); m_view->setMaximumSize(geom.width(),geom.height()); //setMaximumSize(geom.width()+5,geom.height()+10); } } void iotstock::hideMenuBar() { if (!menuBar()->isHidden()) { menuBar()->hide(); } } void iotstock::loadStyle() { qDebug()<<"Loading Stylesheet..."; //Load a simple style... QString fileName; QString path; path = KStandardDirs::locate("appdata", "styles/"); fileName = path + Settings::styleName() + "/simple.qss"; qDebug()<<"Style file:"<<fileName; QFile file(fileName); bool op = file.open(QFile::ReadOnly); QString styleSheet = QLatin1String(file.readAll()); //replace fakepath to the real path.. QString finalStyle = styleSheet.replace("[STYLE_PATH]", path + Settings::styleName() + "/"); qApp->setStyleSheet(finalStyle); if (op) file.close(); } void iotstock::setConnected() { //a workaround.. just to dont modify the code in iotstockview setConnection(true); } void iotstock::setDisconnected() { //a workaround.. just to dont modify the code in iotstockview setConnection(false); } void iotstock::setConnection(bool yes) { if ( yes ) { led->on(); enableUI(); } else { led->off(); disableUI(); } } void iotstock::enableUI() { qDebug()<<"Enabling Actions.."; QAction *action = actionCollection()->action("login"); action->setEnabled(true); if (m_view->isAdminUser()) { qDebug()<<"Enabling for admin"; action = actionCollection()->action("productsBrowse"); action->setEnabled(true); action = actionCollection()->action("offersBrowse"); action->setEnabled(true); action = actionCollection()->action("measuresBrowse"); action->setEnabled(true); action = actionCollection()->action("departmentsBrowse"); action->setEnabled(true); action = actionCollection()->action("categoriesBrowse"); action->setEnabled(true); action = actionCollection()->action("subcategoriesBrowse"); action->setEnabled(true); action = actionCollection()->action("balancesBrowse"); action->setEnabled(true); action = actionCollection()->action("transactionsBrowse"); action->setEnabled(true); action = actionCollection()->action("doPurchase"); action->setEnabled(true); action = actionCollection()->action(KStandardAction::name(KStandardAction::Preferences)); action->setEnabled(true); //action = actionCollection()->action("checkOut"); //action->setEnabled(true); action = actionCollection()->action("reports"); action->setEnabled(true); action = actionCollection()->action("quickViewPlots"); action->setEnabled(true); action = actionCollection()->action("cashFlowBrowse"); action->setEnabled(true); action = actionCollection()->action("stockCorrection"); action->setEnabled(true); action = actionCollection()->action("viewLog"); action->setEnabled(true); action = actionCollection()->action("randomMsgsBrowse"); action->setEnabled(true); action = actionCollection()->action("showSpecialOrders"); action->setEnabled(true); action = actionCollection()->action("printSoldOut"); action->setEnabled(true); action = actionCollection()->action("printLowStock"); action->setEnabled(true); action = actionCollection()->action("printEndOfMonth"); action->setEnabled(true); action = actionCollection()->action("printEndOfDayGral"); action->setEnabled(true); action = actionCollection()->action("printEndOfDay"); action->setEnabled(true); action = actionCollection()->action("currenciesBrowse"); action->setEnabled(true); action = actionCollection()->action("reservationsBrowse"); action->setEnabled(true); } qDebug()<<"Enabling others.."; action = actionCollection()->action("usersBrowse"); action->setEnabled(true); action = actionCollection()->action("clientsBrowse"); action->setEnabled(true); } void iotstock::disableUI() { qDebug()<<"Disabling Actions.."; QAction *action = actionCollection()->action("productsBrowse"); action->setDisabled(true); action = actionCollection()->action("offersBrowse"); action->setDisabled(true); action = actionCollection()->action("measuresBrowse"); action->setDisabled(true); action = actionCollection()->action("departmentsBrowse"); action->setDisabled(true); action = actionCollection()->action("categoriesBrowse"); action->setDisabled(true); action = actionCollection()->action("subcategoriesBrowse"); action->setDisabled(true); action = actionCollection()->action("balancesBrowse"); action->setDisabled(true); action = actionCollection()->action("transactionsBrowse"); action->setDisabled(true); action = actionCollection()->action("doPurchase"); action->setDisabled(true); action = actionCollection()->action(KStandardAction::name(KStandardAction::Preferences)); action->setDisabled(true); action = actionCollection()->action("clientsBrowse"); action->setDisabled(true); action = actionCollection()->action("usersBrowse"); action->setDisabled(true); action = actionCollection()->action("checkOut"); action->setDisabled(true); action = actionCollection()->action("reports"); action->setDisabled(true); action = actionCollection()->action("quickViewPlots"); action->setDisabled(true); action = actionCollection()->action("cashFlowBrowse"); action->setDisabled(true); action = actionCollection()->action("stockCorrection"); action->setDisabled(true); action = actionCollection()->action("viewLog"); action->setDisabled(true); action = actionCollection()->action("randomMsgsBrowse"); action->setDisabled(true); action = actionCollection()->action("showSpecialOrders"); action->setDisabled(true); action = actionCollection()->action("printSoldOut"); action->setDisabled(true); action = actionCollection()->action("printLowStock"); action->setDisabled(true); action = actionCollection()->action("printEndOfMonth"); action->setDisabled(true); action = actionCollection()->action("printEndOfDayGral"); action->setDisabled(true); action = actionCollection()->action("printEndOfDay"); action->setDisabled(true); action = actionCollection()->action("currenciesBrowse"); action->setDisabled(true); action = actionCollection()->action("reservationsBrowse"); action->setDisabled(true); } void iotstock::setupActions() { KStandardAction::quit(qApp, SLOT(quit()), actionCollection()); KStandardAction::preferences(this, SLOT(optionsPreferences()), actionCollection()); //My actions QAction* loginAction = actionCollection()->addAction( "login" ); loginAction->setText(i18n("Login")); loginAction->setIcon(KIcon("office-address-book")); loginAction->setShortcut(Qt::CTRL+Qt::Key_L); connect(loginAction, SIGNAL(triggered(bool)),m_view, SLOT(login())); QAction* usersBrowseAction = actionCollection()->addAction( "usersBrowse" ); usersBrowseAction->setText(i18n("Users")); usersBrowseAction->setIcon(KIcon("iotpos-user")); usersBrowseAction->setShortcut(Qt::CTRL+Qt::Key_U); connect(usersBrowseAction, SIGNAL(triggered(bool)),m_view, SLOT(showUsersPage())); QAction* clientsBrowseAction = actionCollection()->addAction( "clientsBrowse" ); clientsBrowseAction->setText(i18n("Clients")); clientsBrowseAction->setIcon(KIcon("iotpos-user"));//TODO:Create an icon for this... clientsBrowseAction->setShortcut(Qt::CTRL+Qt::Key_I); connect(clientsBrowseAction, SIGNAL(triggered(bool)),m_view, SLOT(showClientsPage())); QAction* prodBrowseAction = actionCollection()->addAction( "productsBrowse" ); prodBrowseAction->setText(i18n("Products")); prodBrowseAction->setIcon(KIcon("iotpos-box")); prodBrowseAction->setShortcut(Qt::CTRL+Qt::Key_P); connect(prodBrowseAction, SIGNAL(triggered(bool)),m_view, SLOT(showProductsPage())); QAction* measuresBrowseAction = actionCollection()->addAction( "measuresBrowse" ); measuresBrowseAction->setText(i18n("Measures")); measuresBrowseAction->setIcon(KIcon("iotpos-ruler")); measuresBrowseAction->setShortcut(Qt::CTRL+Qt::Key_M); connect(measuresBrowseAction, SIGNAL(triggered(bool)),m_view, SLOT(showMeasuresPage())); QAction* departmentsBrowseAction = actionCollection()->addAction( "departmentsBrowse" ); departmentsBrowseAction->setText(i18n("Departments")); departmentsBrowseAction->setIcon(KIcon("iotpos-categories")); departmentsBrowseAction->setShortcut(Qt::CTRL+Qt::Key_C); connect(departmentsBrowseAction, SIGNAL(triggered(bool)),m_view, SLOT(showDepartmentsPage())); QAction* categoriesBrowseAction = actionCollection()->addAction( "categoriesBrowse" ); categoriesBrowseAction->setText(i18n("Categories")); categoriesBrowseAction->setIcon(KIcon("iotpos-categories")); categoriesBrowseAction->setShortcut(Qt::CTRL+Qt::Key_C); connect(categoriesBrowseAction, SIGNAL(triggered(bool)),m_view, SLOT(showCategoriesPage())); QAction* subcategoriesBrowseAction = actionCollection()->addAction( "subcategoriesBrowse" ); subcategoriesBrowseAction->setText(i18n("Subcategories")); subcategoriesBrowseAction->setIcon(KIcon("iotpos-categories")); subcategoriesBrowseAction->setShortcut(Qt::CTRL+Qt::Key_S); //see if it not causes troubles... CTRL-S connect(subcategoriesBrowseAction, SIGNAL(triggered(bool)),m_view, SLOT(showSubCategoriesPage())); QAction* offersBrowseAction = actionCollection()->addAction( "offersBrowse" ); offersBrowseAction->setText(i18n("Offers")); offersBrowseAction->setIcon(KIcon("iotpos-offers")); offersBrowseAction->setShortcut(Qt::CTRL+Qt::Key_O); connect(offersBrowseAction, SIGNAL(triggered(bool)),m_view, SLOT(showOffersPage())); QAction* balancesBrowseAction = actionCollection()->addAction( "balancesBrowse" ); balancesBrowseAction->setText(i18n("Balances")); balancesBrowseAction->setIcon(KIcon("iotposbalance")); balancesBrowseAction->setShortcut(Qt::CTRL+Qt::Key_B); connect(balancesBrowseAction, SIGNAL(triggered(bool)),m_view, SLOT(showBalancesPage())); QAction* cashFlowBrowseAction = actionCollection()->addAction( "cashFlowBrowse" ); cashFlowBrowseAction->setText(i18n("Cash Flow")); cashFlowBrowseAction->setIcon(KIcon("iotpos-cashout")); cashFlowBrowseAction->setShortcut(Qt::CTRL+Qt::Key_F); connect(cashFlowBrowseAction, SIGNAL(triggered(bool)),m_view, SLOT(showCashFlowPage())); QAction* transactionsBrowseAction = actionCollection()->addAction( "transactionsBrowse" ); transactionsBrowseAction->setText(i18n("Transactions")); transactionsBrowseAction->setIcon(KIcon("wallet-open")); transactionsBrowseAction->setShortcut(Qt::CTRL+Qt::Key_T); connect(transactionsBrowseAction, SIGNAL(triggered(bool)),m_view, SLOT(showTransactionsPage())); QAction* quickViewPlotsAction = actionCollection()->addAction( "quickViewPlots" ); quickViewPlotsAction->setText(i18n("Quick Plots")); quickViewPlotsAction->setIcon(KIcon("view-statistics")); quickViewPlotsAction->setShortcut(Qt::CTRL+Qt::Key_W); connect(quickViewPlotsAction, SIGNAL(triggered(bool)),m_view, SLOT(showWelcomeGraphs())); QAction* purchaseAction = actionCollection()->addAction( "doPurchase" ); //Alias Check IN purchaseAction->setText(i18n("Purchase")); purchaseAction->setIcon(KIcon("iotpos-box")); purchaseAction->setShortcut(Qt::Key_F2); connect(purchaseAction, SIGNAL(triggered(bool)),m_view, SLOT(doPurchase())); QAction* checkOutAction = actionCollection()->addAction( "checkOut" ); checkOutAction->setText(i18n("Check Out")); checkOutAction->setIcon(KIcon("iotpos-money"));//TODO:Create an icon for this... checkOutAction->setShortcut(Qt::Key_F3); connect(checkOutAction, SIGNAL(triggered(bool)),m_view, SLOT(doCheckOut())); QAction* stockCorrectionAction = actionCollection()->addAction( "stockCorrection" ); stockCorrectionAction->setText(i18n("Stock Correction")); stockCorrectionAction->setIcon(KIcon("iotpos-box"));//TODO:Create an icon for this... stockCorrectionAction->setShortcut(Qt::Key_F4); connect(stockCorrectionAction, SIGNAL(triggered(bool)),m_view, SLOT(stockCorrection())); QAction* reportsAction = actionCollection()->addAction( "reports" ); reportsAction->setText(i18n("Reports")); reportsAction->setIcon(KIcon("iotpos-reports")); reportsAction->setShortcut(Qt::Key_F5); connect(reportsAction, SIGNAL(triggered(bool)),m_view, SLOT(showReports())); QAction *action = actionCollection()->addAction( "printEndOfDay" ); action->setText(i18n("Print End of day report")); action->setIcon(KIcon("iotpos-reports")); action->setShortcut(Qt::Key_F6); connect(action, SIGNAL(triggered(bool)),m_view, SLOT(printEndOfDay())); action = actionCollection()->addAction( "printEndOfDayGral" ); action->setText(i18n("Print General end of day report")); action->setIcon(KIcon("iotpos-reports")); action->setShortcut(Qt::Key_F7); connect(action, SIGNAL(triggered(bool)),m_view, SLOT(printGralEndOfDay())); action = actionCollection()->addAction( "printEndOfMonth" ); action->setText(i18n("Print End of month report")); action->setIcon(KIcon("iotpos-reports")); action->setShortcut(Qt::Key_F8); connect(action, SIGNAL(triggered(bool)),m_view, SLOT(printEndOfMonth())); action = actionCollection()->addAction( "printLowStock" ); action->setText(i18n("Print Low stock products")); action->setIcon(KIcon("iotpos-reports")); action->setShortcut(Qt::Key_F9); connect(action, SIGNAL(triggered(bool)),m_view, SLOT(printLowStockProducts())); action = actionCollection()->addAction( "printSoldOut" ); action->setText(i18n("Print Sold out products")); action->setIcon(KIcon("iotpos-reports")); action->setShortcut(Qt::Key_F10); connect(action, SIGNAL(triggered(bool)),m_view, SLOT(printSoldOutProducts())); action = actionCollection()->addAction( "showSpecialOrders" ); action->setText(i18n("Show Special Orders")); action->setIcon(KIcon("iotpos-box")); //FIXME: Create an ICON action->setShortcut(Qt::Key_Insert); connect(action, SIGNAL(triggered(bool)),m_view, SLOT(showSpecialOrders())); action = actionCollection()->addAction( "randomMsgsBrowse" ); action->setText(i18n("Ticket Messages")); action->setIcon(KIcon("iotpos-ticket")); action->setShortcut(Qt::CTRL+Qt::Key_M); connect(action, SIGNAL(triggered(bool)),m_view, SLOT(showRandomMsgs())); action = actionCollection()->addAction( "viewLog" ); action->setText(i18n("View Events Log")); action->setIcon(KIcon("view-pim-tasks-pending")); action->setShortcut(Qt::CTRL+Qt::Key_G); connect(action, SIGNAL(triggered(bool)),m_view, SLOT(showLogs())); action = actionCollection()->addAction( "currenciesBrowse" ); action->setText(i18n("View Currencies")); action->setIcon(KIcon("iotpos-money")); action->setShortcut(Qt::ALT+Qt::Key_C); connect(action, SIGNAL(triggered(bool)),m_view, SLOT(showCurrencies())); action = actionCollection()->addAction( "reservationsBrowse" ); action->setText(i18n("View Reservations")); action->setIcon(KIcon("iotpos-box")); action->setShortcut(Qt::ALT+Qt::Key_R); connect(action, SIGNAL(triggered(bool)),m_view, SLOT(showReservations())); } /**This is used to get Database user,password,server to set initial config, in case the db server is remote. So we show the config dialog, and when saved login again. It is called from main_view.login() **/ void iotstock::showDBConfigDialog() { //avoid to have 2 dialogs shown if ( KConfigDialog::showDialog( "settings" ) ) { return; } KConfigDialog *dialog = new KConfigDialog(this, "settings", Settings::self()); QWidget *dbSettingsDlg = new QWidget; ui_prefs_db.setupUi(dbSettingsDlg); dialog->addPage(dbSettingsDlg, i18n("Database"), "vcs_diff"); //kexi connect(dialog, SIGNAL(settingsChanged(QString)), m_view, SLOT(settingsChangedOnInitConfig())); dialog->setAttribute( Qt::WA_DeleteOnClose ); dialog->show(); } void iotstock::optionsPreferences() { //avoid to have 2 dialogs shown if ( KConfigDialog::showDialog( "settings" ) ) { return; } KConfigDialog *dialog = new KConfigDialog(this, "settings", Settings::self()); //general QWidget *generalSettingsDlg = new QWidget; ui_prefs_base.setupUi(generalSettingsDlg); dialog->addPage(generalSettingsDlg, i18n("General"), "configure"); //Database QWidget *dbSettingsDlg = new QWidget; ui_prefs_db.setupUi(dbSettingsDlg); dialog->addPage(dbSettingsDlg, i18n("Database"), "kexi"); //Printers QWidget *printerSettingsDlg = new QWidget; ui_pref_printers.setupUi(printerSettingsDlg); dialog->addPage(printerSettingsDlg, i18n("Printers"), "iotpos-printer"); connect(dialog, SIGNAL(settingsChanged(QString)), m_view, SLOT(settingsChanged())); //free mem by deleting the dialog on close without waiting for deletingit when the application quits dialog->setAttribute( Qt::WA_DeleteOnClose ); dialog->show(); } void iotstock::changeStatusbar(const QString& text) { // display the text on the statusbar statusBar()->showMessage(text); } void iotstock::changeCaption(const QString& text) { // display the text on the caption setCaption(text); } bool iotstock::queryClose() { m_view->closeDB(); return true; } void iotstock::salir() { qApp->quit(); } #include "iotstock.moc"
22,294
C++
.cpp
472
43.139831
136
0.703719
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
752,833
producteditor.cpp
hiramvillarreal_iotpos/iotstock/src/producteditor.cpp
/************************************************************************** * Copyright © 2013-2015 by Hiram R. Villarreal * * hiramvillarreal.ap@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include <KLocale> #include <KMessageBox> #include <KFileDialog> #include <KStandardDirs> #include <QByteArray> #include <QRegExpValidator> #include <QRegExp> #include <QtSql> //#include <QFile> #include "producteditor.h" #include "subcategoryeditor.h" #include "../../dataAccess/azahar.h" #include "../../src/inputdialog.h" #include "../../mibitWidgets/mibittip.h" #include "../../mibitWidgets/mibitfloatpanel.h" #include <iostream> #include <fstream> ProductEditorUI::ProductEditorUI( QWidget *parent ) : QFrame( parent ) { setupUi( this ); } ProductEditor::ProductEditor( QWidget *parent, bool newProduct ) : KDialog( parent ) { oldStockQty = 0; correctingStockOk = false; m_modelAssigned = false; groupInfo.isAvailable = true; groupInfo.cost = 0; groupInfo.price = 0; groupInfo.name = ""; groupInfo.tax = 0; groupInfo.taxMoney = 0; ui = new ProductEditorUI( this ); setMainWidget( ui ); setCaption( i18n("Product Editor") ); setButtons( KDialog::Ok|KDialog::Cancel ); QString path = KStandardDirs::locate("appdata", "styles/"); path = path+"tip.svg"; errorPanel = new MibitTip(this, ui->editCode, path, DesktopIcon("dialog-warning", 32)); errorPanel->setMaxHeight(65); errorAlphacode = new MibitTip(this, ui->editAlphacode, path, DesktopIcon("dialog-warning", 32)); errorAlphacode->setMaxHeight(65); errorVendorcode = new MibitTip(this, ui->editVendorcode, path, DesktopIcon("dialog-warning", 32)); errorVendorcode->setMaxHeight(65); path = KStandardDirs::locate("appdata", "styles/"); path = path+"floating_bottom.svg"; groupPanel = new MibitFloatPanel(this, path, Bottom); groupPanel->setSize(460,250); groupPanel->addWidget(ui->groupsPanel); groupPanel->setMode(pmManual); groupPanel->setHiddenTotally(true); ui->btnShowGroup->setDisabled(true); ui->btnChangeCode->setIcon(QIcon(DesktopIcon("edit-clear", 32))); ui->printBC->setIcon(QIcon(DesktopIcon("iotpos-tag", 32))); //Set Validators for input boxes QRegExp regexpC("[0-9]{1,13}"); //(EAN-13 y EAN-8) .. y productos sin codigo de barras? QRegExpValidator * validatorEAN13 = new QRegExpValidator(regexpC, this); ui->editCode->setValidator(validatorEAN13); ui->editUtility->setValidator(new QDoubleValidator(0.00, 999999999999.99, 3,ui->editUtility)); ui->editTax->setValidator(new QDoubleValidator(0.00, 999999999999.99, 3,ui->editTax)); ui->editExtraTaxes->setValidator(new QDoubleValidator(0.00, 999999999999.99, 3,ui->editExtraTaxes)); ui->editCost->setValidator(new QDoubleValidator(0.00, 999999999999.99, 3, ui->editCost)); ui->editStockQty->setValidator(new QDoubleValidator(0.00,999999999999.99, 3, ui->editStockQty)); ui->editPoints->setValidator(new QIntValidator(0,999999999, ui->editPoints)); ui->editFinalPrice->setValidator(new QDoubleValidator(0.00,999999999999.99, 3, ui->editFinalPrice)); QRegExp regexpAC("[0-9]*[//.]{0,1}[0-9]{0,2}[//*]{0,1}[0-9]*[A-Za-z_0-9\\\\/\\-]{0,30}"); // Instead of {0,13} fro EAN13, open for up to 30 chars. QRegExpValidator * validatorAC = new QRegExpValidator(regexpAC, this); ui->editAlphacode->setValidator(validatorAC); ui->editVendorcode->setValidator(validatorAC); //the same validator as alphacode. connect( ui->btnPhoto , SIGNAL( clicked() ), this, SLOT( changePhoto() ) ); connect( ui->btnCalculatePrice , SIGNAL( clicked() ), this, SLOT( calculatePrice() ) ); connect( ui->btnChangeCode, SIGNAL( clicked() ), this, SLOT( changeCode() ) ); connect( ui->editCode, SIGNAL(textEdited(const QString &)), SLOT(checkIfCodeExists())); connect( ui->editCode, SIGNAL(editingFinished()), this, SLOT(checkFieldsState())); connect( ui->editCode, SIGNAL(returnPressed()), this, SLOT(checkFieldsState())); connect( ui->btnStockCorrect, SIGNAL( clicked() ), this, SLOT( modifyStock() )); connect( ui->printBC, SIGNAL( clicked() ), this, SLOT( printBarcode() )); connect( ui->editDesc, SIGNAL(editingFinished()), this, SLOT(checkFieldsState())); connect( ui->editStockQty, SIGNAL(editingFinished()), this, SLOT(checkFieldsState())); connect( ui->editPoints, SIGNAL(editingFinished()), this, SLOT(checkFieldsState())); connect( ui->editCost, SIGNAL(editingFinished()), this, SLOT(checkFieldsState())); connect( ui->editTax, SIGNAL(editingFinished()), this, SLOT(checkFieldsState())); connect( ui->editExtraTaxes, SIGNAL(editingFinished()), this, SLOT(checkFieldsState())); connect( ui->editFinalPrice, SIGNAL(textChanged(const QString &)), SLOT(checkFieldsState())); connect( ui->chIsAGroup, SIGNAL(clicked(bool)), SLOT(toggleGroup(bool)) ); connect( ui->chIsARaw, SIGNAL(clicked(bool)), SLOT(toggleRaw(bool)) ); connect( ui->btnCloseGroup, SIGNAL(clicked()), groupPanel, SLOT(hidePanel()) ); connect( ui->btnCloseGroup, SIGNAL(clicked()), this, SLOT(checkFieldsState()) ); connect( ui->btnShowGroup, SIGNAL(clicked()), groupPanel, SLOT(showPanel()) ); connect( ui->editFilter, SIGNAL(textEdited ( const QString &)), SLOT(applyFilter(const QString &)) ); connect( ui->btnAdd, SIGNAL(clicked()), SLOT(addItem()) ); connect( ui->btnRemove, SIGNAL(clicked()), SLOT(removeItem()) ); connect( ui->groupView, SIGNAL(itemDoubleClicked(QTableWidgetItem*)), SLOT(itemDoubleClicked(QTableWidgetItem*)) ); connect( ui->editGroupPriceDrop, SIGNAL(valueChanged(double)), SLOT(updatePriceDrop(double)) ); connect( ui->editFinalPrice, SIGNAL(textChanged(QString) ), SLOT(calculateProfit(QString)) ); connect( ui->chUnlimitedStock, SIGNAL(clicked(bool)), SLOT(setUnlimitedStock(bool)) ); connect( ui->chRise, SIGNAL(clicked(bool)), SLOT(on_chRise_clicked(bool)) ); connect( ui->editAlphacode, SIGNAL(textEdited(const QString &)), this, SLOT(verifyAlphacodeDuplicates()) ); connect( ui->editVendorcode, SIGNAL(textEdited(const QString &)), this, SLOT(verifyVendorcodeDuplicates()) ); connect( ui->departmentsCombo, SIGNAL(currentIndexChanged( int )), SLOT(modifyDepartment()) ); connect( ui->categoriesCombo, SIGNAL(currentIndexChanged( int )), SLOT(modifyCategory()) ); connect( ui->btnCreateCategory, SIGNAL(clicked()), SLOT(createNewCategory()) ); connect( ui->btnCreateSubcategory, SIGNAL(clicked()), SLOT(createNewSubcategory()) ); connect( ui->btnCreateDepartment, SIGNAL(clicked()), SLOT(createNewDepartment()) ); connect( ui->btnCreateMeasure, SIGNAL(clicked()), SLOT(createNewMeasure()) ); status = statusNormal; modifyCode = false; autoCode = newProduct; if (newProduct) { ui->labelStockQty->setText(i18n("Purchase Qty:")); disableStockCorrection(); qDebug()<<"Adding new product, autocalulate code:"<<autoCode; if (autoCode) { qulonglong c = getNextCode(); ui->editCode->setText(QString::number(c)); qDebug()<<"Got next code:"<<c; ui->editAlphacode->setFocus(); } } else ui->labelStockQty->setText(i18n("Stock Qty:")); QTimer::singleShot(350, this, SLOT(checkIfCodeExists())); QTimer::singleShot(450, this, SLOT(applyFilter())); ui->editStockQty->setText("0.0"); ui->editPoints->setText("0.0"); ui->editExtraTaxes->setText("0.0"); ui->lEditBC -> setText("1"); autoCode = false; } ProductEditor::~ProductEditor() { //remove products filter m_model->setFilter(""); m_model->select(); delete ui; } void ProductEditor::applyFilter(const QString &text) { QRegExp regexp = QRegExp(text); if (!regexp.isValid()) ui->editFilter->setText(""); if (ui->chIsAGroup->isChecked()) { if (text == "*" || text == "") m_model->setFilter("products.isAGroup=0 AND products.isARawProduct=0"); else m_model->setFilter(QString("products.name REGEXP '%1' AND products.isAGroup=0 AND products.isARawProduct=0").arg(text)); } else { m_model->setFilter(""); } m_model->select(); } void ProductEditor::applyFilter() { if (ui->chIsAGroup->isChecked()) { m_model->setFilter("products.isAGroup=0 AND products.isARawProduct=0"); } else { m_model->setFilter(""); } m_model->select(); } void ProductEditor::setDb(QSqlDatabase database) { db = database; if (!db.isOpen()) db.open(); populateDepartmentsCombo(); //populateCategoriesCombo(); categories and subcategories is called by the above. populateMeasuresCombo(); } void ProductEditor::populateDepartmentsCombo() { Azahar *myDb = new Azahar; myDb->setDatabase(db); ui->departmentsCombo->clear(); ui->departmentsCombo->addItems(myDb->getDepartmentsList()); populateCategoriesCombo(); //call populateCategoriesCombo also! delete myDb; } void ProductEditor::populateCategoriesCombo() { Azahar *myDb = new Azahar; myDb->setDatabase(db); ui->categoriesCombo->clear(); ui->categoriesCombo->addItems(myDb->getCategoriesList()); populateSubCategoriesCombo(); //call populateSubcategoriesCombo also! delete myDb; } void ProductEditor::populateSubCategoriesCombo() { Azahar *myDb = new Azahar; myDb->setDatabase(db); ui->subcategoriesCombo->clear(); ui->subcategoriesCombo->addItems(myDb->getSubCategoriesList()); delete myDb; } void ProductEditor::populateMeasuresCombo() { Azahar *myDb = new Azahar; myDb->setDatabase(db); ui->measuresCombo->clear(); ui->measuresCombo->addItems(myDb->getMeasuresList()); delete myDb; } int ProductEditor::getDepartmentId() { int code=-1; QString currentText = ui->departmentsCombo->currentText(); Azahar *myDb = new Azahar; myDb->setDatabase(db); code = myDb->getDepartmentId(currentText); delete myDb; return code; } int ProductEditor::getCategoryId() { int code=-1; QString currentText = ui->categoriesCombo->currentText(); Azahar *myDb = new Azahar; myDb->setDatabase(db); code = myDb->getCategoryId(currentText); delete myDb; return code; } int ProductEditor::getSubCategoryId() { int code=-1; QString currentText = ui->subcategoriesCombo->currentText(); Azahar *myDb = new Azahar; myDb->setDatabase(db); code = myDb->getSubCategoryId(currentText); delete myDb; return code; } //returns the parent category id of a subcategory. int ProductEditor::getSubCategoryParent() { int code=-1; QString currentText = ui->categoriesCombo->currentText(); //get category Azahar *myDb = new Azahar; myDb->setDatabase(db); code = myDb->getCategoryId(currentText); delete myDb; return code; } int ProductEditor::getMeasureId() { int code=-1; QString currentText = ui->measuresCombo->currentText(); Azahar *myDb = new Azahar; myDb->setDatabase(db); code = myDb->getMeasureId(currentText); delete myDb; return code; } void ProductEditor::setDepartment(QString str) { int idx = ui->departmentsCombo->findText(str,Qt::MatchCaseSensitive); if (idx > -1) ui->departmentsCombo->setCurrentIndex(idx); else { qDebug()<<"Department not found:"<<str; } } void ProductEditor::setCategory(QString str) { int idx = ui->categoriesCombo->findText(str,Qt::MatchCaseSensitive); if (idx > -1) ui->categoriesCombo->setCurrentIndex(idx); else { qDebug()<<"Category not found:"<<str; } } void ProductEditor::setSubCategory(QString str) { if (str == "") {ui->subcategoriesCombo->setCurrentIndex(0); return;} int idx = ui->subcategoriesCombo->findText(str,Qt::MatchCaseSensitive); if (idx > -1) ui->subcategoriesCombo->setCurrentIndex(idx); else { qDebug()<<"SubCategory not found:"<<str; } } void ProductEditor::setDepartment(int i) { QString text = getDepartmentStr(i); setDepartment(text); qDebug()<<"SET DEPARTMENT INT :: Department Id:"<<i<<" Name:"<<text; } void ProductEditor::setCategory(int i) { QString text = getCategoryStr(i); setCategory(text); qDebug()<<"SET CATEGORY INT :: Category Id:"<<i<<" Name:"<<text; } void ProductEditor::setSubCategory(int i) { QString text = getSubCategoryStr(i); setSubCategory(text); qDebug()<<"SET SUBCATEGORY INT :: Category Id:"<<i<<" Name:"<<text; } //NOTE:This maybe is duplicated, because the ProducInfo already contains a category. Parent in subcategory is a pointer to the category. Both must be the same. void ProductEditor::setSubCategoryParent(int parentId) { Azahar *myDb = new Azahar; myDb->setDatabase(db); QString text = myDb->getCategoryStr(parentId); setSubCategory(text); qDebug()<<"SET SUBCATEGORY PARENT INT :: Category Id:"<<parentId<<" Parent Name:"<<text; delete myDb; } void ProductEditor::setMeasure(int i) { QString text = getMeasureStr(i); setMeasure(text); } void ProductEditor::setMeasure(QString str) { int idx = ui->measuresCombo->findText(str,Qt::MatchCaseSensitive); if (idx > -1) ui->measuresCombo->setCurrentIndex(idx); else { qDebug()<<"Measure not found:"<<str; } } QString ProductEditor::getDepartmentStr(int c) { Azahar *myDb = new Azahar; myDb->setDatabase(db); QString str = myDb->getDepartmentStr(c); delete myDb; return str; } QString ProductEditor::getCategoryStr(int c) { Azahar *myDb = new Azahar; myDb->setDatabase(db); QString str = myDb->getCategoryStr(c); delete myDb; return str; } QString ProductEditor::getSubCategoryStr(int c) { Azahar *myDb = new Azahar; myDb->setDatabase(db); QString str = myDb->getSubCategoryStr(c); qDebug()<<"Getting subcategory #"<<c<<" -- "<<str; delete myDb; return str; } QString ProductEditor::getMeasureStr(int c) { Azahar *myDb = new Azahar; myDb->setDatabase(db); QString str = myDb->getMeasureStr(c); delete myDb; return str; } void ProductEditor::changePhoto() { QString fname = KFileDialog::getOpenFileName(); if (!fname.isEmpty()) { QPixmap p = QPixmap(fname); setPhoto(p); } } void ProductEditor::calculatePrice() { double finalPrice=0.0; if (ui->editCost->text().isEmpty()) { ui->editCost->setFocus(); } else if (ui->editUtility->text().isEmpty()) { ui->editUtility->setFocus(); } else if (ui->editTax->text().isEmpty()) { ui->editTax->setText("0.0"); ui->editTax->setFocus(); ui->editTax->selectAll(); } else { if (ui->editExtraTaxes->text().isEmpty()) { ui->editExtraTaxes->setText("0.0"); ui->editExtraTaxes->setFocus(); ui->editExtraTaxes->selectAll(); } Azahar *myDb = new Azahar; myDb->setDatabase(db); bool taxIncluded = myDb->getConfigTaxIsIncludedInPrice(); delete myDb; double cost = ui->editCost->text().toDouble(); double profit = ui->editUtility->text().toDouble(); double tax = ui->editTax->text().toDouble(); double tax2 = ui->editExtraTaxes->text().toDouble(); //Profit is calculated before taxes... profit = ((profit/100)*cost); double cu = cost + profit; //FIXME: Taxes include profit... is it ok? tax = ((tax/100)*cu); tax2 = ((tax2/100)*cu); /** @note: taxIncludedInPrice means that the product.price has embedded the tax already, and it is not necessary to add it at the time we are selling. * So, here (editing product price) when using autocalculate price, when taxIncluded=true we need to embed the tax in the price. * It is just the opposite way we do in iotpos when selling (taxIncluded=true --> DO NOT add taxes). **/ if (taxIncluded) finalPrice = cost + profit + tax + tax2; else finalPrice = cost + profit; qDebug()<<"Profit:"<<profit<<" Cost + profit:"<<cu<<" Taxes:"<<tax+tax2<<" Final Price: $"<<finalPrice; // BFB: avoid more than 2 decimal digits in finalPrice. Round. ui->editFinalPrice->setText(QString::number(finalPrice,'f',2)); ui->editFinalPrice->selectAll(); ui->editFinalPrice->setFocus(); } } void ProductEditor::calculateProfit(QString amountStr) { double amount = amountStr.toDouble(); if (amount >0) { double profit = 0; double profitMoney = 0; double cost = 0; double pWOtax = 0; Azahar *myDb = new Azahar; myDb->setDatabase(db); bool taxIsIncluded = myDb->getConfigTaxIsIncludedInPrice(); cost = ui->editCost->text().toDouble(); if ( taxIsIncluded ) pWOtax= ui->editFinalPrice->text().toDouble()/(1+((ui->editTax->text().toDouble()+ui->editExtraTaxes->text().toDouble())/100)); else pWOtax = ui->editFinalPrice->text().toDouble(); //TODO:use the pWOtax profitMoney = ( pWOtax - cost ); profit = ( profitMoney / cost ); //qDebug()<<" calculateProfit() Profit % "<<profit<<" Profit $ "<<profitMoney<<" Price Without Taxes:"<<pWOtax<<" Cost + profit:"<<cost+profitMoney; ui->lblProfit->setText(i18n("Gross Profit: %1% (%2)", QString::number(profit*100, 'f', 2) , KGlobal::locale()->formatMoney(profitMoney, QString(), 2) )); } else { ui->lblProfit->clear(); } } void ProductEditor::changeCode() { //this enables the code editing... to prevent unwanted code changes... enableCode(); ui->editCode->setFocus(); ui->editCode->selectAll(); } void ProductEditor::modifyStock() { if ( isGroup() || hasUnlimitedStock() ) { //simply dont allow or show a message? return; } double newStockQty=0; oldStockQty = ui->editStockQty->text().toDouble(); bool ok = false; InputDialog *dlg = new InputDialog(this, false, dialogStockCorrection, i18n("Enter the quantity and reason for the change, then press <ENTER> to accept, <ESC> to cancel")); dlg->setProductCode(ui->editCode->text().toULongLong()); dlg->setAmount(ui->editStockQty->text().toDouble()); dlg->setProductCodeReadOnly(); if (dlg->exec()) { newStockQty = dlg->dValue; reason = dlg->reason; ok = true; } if (ok) { //send data to database... ui->editStockQty->setText( QString::number(newStockQty) ); //update this info on producteditor correctingStockOk = ok; } } void ProductEditor::printBarcode(){ //std::ofstream fOut("/home/iotpos/printing/iotstock_spool"); std::ofstream fOut("/home/pi/iotpos/printing/spool"); if (fOut.is_open()){ // int n = ui-> lEditBC ->text().toInt() ; QProcess process; fOut << ui->editDesc->text().toStdString() << '\n'; fOut << ui->editFinalPrice->text().toDouble() << '\n'; fOut << ui->editCode->text().toULongLong() <<'\n'; fOut << ui->lEditBC->text().toULongLong(); process.startDetached("python", QStringList()<< "/home/pi/iotpos/py-thermal-printer-master/printerlabel.py"); // for(int i=0; i <n; i++){ //process.startDetached("python", QStringList()<< "/home/pi/iotpos/py-thermal-printer-master/printerlabel.py"); // } fOut.close(); } } void ProductEditor::checkIfCodeExists() { enableButtonOk( false ); QString codeStr = ui->editCode->text(); if (codeStr.isEmpty()) { codeStr="-1"; } Azahar *myDb = new Azahar; myDb->setDatabase(db); ProductInfo pInfo = myDb->getProductInfo(codeStr); if (pInfo.isAGroup) { // get it again with the appropiate tax and price. pInfo = myDb->getProductInfo(codeStr, true); //the 2nd parameter is to get the taxes for the group (not considering discounts) } if (pInfo.code > 0) { //code exists... status = statusMod; if (!modifyCode){ //Prepopulate dialog... ui->editAlphacode->setText( pInfo.alphaCode ); ui->editVendorcode->setText( pInfo.vendorCode ); ui->editDesc->setText(pInfo.desc); ui->editStockQty->setText(QString::number(pInfo.stockqty)); setDepartment(pInfo.department); setCategory(pInfo.category); setSubCategory(pInfo.subcategory); setMeasure(pInfo.units); ui->editCost->setText(QString::number(pInfo.cost)); ui->editTax->setText(QString::number(pInfo.tax)); ui->editExtraTaxes->setText(QString::number(pInfo.extratax)); ui->editFinalPrice->setText(QString::number(pInfo.price)); ui->editPoints->setText(QString::number(pInfo.points)); ui->btnShowGroup->setEnabled(pInfo.isAGroup); ui->btnStockCorrect->setDisabled(pInfo.isAGroup); //dont allow grouped products to make stock correction ui->chIsARaw->setChecked(pInfo.isARawProduct); setUnlimitedStock(pInfo.hasUnlimitedStock); setNotDiscountable(pInfo.isNotDiscountable); if (pInfo.isAGroup) { setIsAGroup(pInfo.isAGroup); setGroupElements(pInfo); } if (!pInfo.photo.isEmpty()) { QPixmap photo; photo.loadFromData(pInfo.photo); setPhoto(photo); } }//if !modifyCode else { errorPanel->showTip(i18n("Code %1 already exists.", codeStr),3000); enableButtonOk( false ); } } else { //code does not exists... its a new product status = statusNormal; if (!modifyCode) { //clear all used edits ui->editAlphacode->clear(); ui->editVendorcode->clear(); ui->editDesc->clear(); ui->editStockQty->clear(); setDepartment(1); setCategory(1); setSubCategory(1); setMeasure(1); ui->editCost->clear(); ui->editTax->clear(); ui->editExtraTaxes->clear(); ui->editFinalPrice->clear(); ui->editPoints->clear(); ui->editUtility->clear(); ui->editFinalPrice->clear(); ui->labelPhoto->setText("No Photo"); } //qDebug()<< "no product found with code "<<codeStr<<" .query.size()=="<<query.size(); } delete myDb; } void ProductEditor::checkFieldsState() { bool ready = false; if ( !ui->editCode->text().isEmpty() && !ui->editDesc->text().isEmpty() && //!ui->editStockQty->text().isEmpty() && Comment: This requirement was removed in order to use check-in/check-out procedures. !ui->editPoints->text().isEmpty() && !ui->editCost->text().isEmpty() && !ui->editTax->text().isEmpty() && !ui->editExtraTaxes->text().isEmpty() && !ui->editFinalPrice->text().isEmpty() && ui->editTax->text().toDouble() >= 0 /// See Ticket #74. Allow ZERO tax for some products. ) { ready = true; } enableButtonOk(ready); if (!ready && ui->editCode->hasFocus() && ui->editCode->isReadOnly() ) { ui->editDesc->setFocus(); } } void ProductEditor::setPhoto(QPixmap p) { int max = 150; QPixmap newPix; if ((p.height() > max) || (p.width() > max) ) { if (p.height() == p.width()) { newPix = p.scaled(QSize(max, max)); } else if (p.height() > p.width() ) { newPix = p.scaledToHeight(max); } else { newPix = p.scaledToWidth(max); } } else newPix=p; ui->labelPhoto->setPixmap(newPix); pix=newPix; } void ProductEditor::slotButtonClicked(int button) { if (button == KDialog::Ok) { if (status == statusNormal) QDialog::accept(); else { qDebug()<< "Button = OK, status == statusMOD"; done(statusMod); } } else QDialog::reject(); } void ProductEditor::setModel(QSqlRelationalTableModel *model) { ui->sourcePView->setModel(model); ui->sourcePView->setModelColumn(1); m_model = model; m_modelAssigned = true; //clear any filter m_model->setFilter(""); m_model->setFilter("products.isAGroup=0 AND products.isARawProduct=0"); m_model->select(); } void ProductEditor::addItem() { Azahar *myDb = new Azahar; myDb->setDatabase(db); groupInfo.count = 0; groupInfo.cost = 0; groupInfo.price = 0; groupInfo.tax = 0; groupInfo.taxMoney = 0; double addQty = 0; addQty = ui->editGroupQty->value(); //get selected items from source view QItemSelectionModel *selectionModel = ui->sourcePView->selectionModel(); QModelIndexList indexList = selectionModel->selectedRows(); // pasar el indice que quiera (0=code, 1=name) foreach(QModelIndex index, indexList) { qulonglong code = index.data().toULongLong(); QString codeStr = index.data().toString(); ProductInfo pInfo; //get product info from hash or db if (groupInfo.productsList.contains(code)) { pInfo = groupInfo.productsList.take(code); if ( pInfo.units == 1 ) pInfo.qtyOnList += int(addQty); //increment it (PIECES) else pInfo.qtyOnList += addQty; //increment it (OTHER MEASURES) } else { pInfo = myDb->getProductInfo(codeStr, true); //the 2nd parameter is to get the taxes for the group (not considering discounts) if ( pInfo.units == 1 ) pInfo.qtyOnList = int(addQty); //increment it (PIECES) else pInfo.qtyOnList = addQty; //increment it (OTHER MEASURES) } //check if the product to be added is not the same of the pack product if (pInfo.code == ui->editCode->text().toULongLong()) continue; // Insert product to the group hash groupInfo.productsList.insert(code, pInfo); } //reload groupView updatePriceDrop(ui->editGroupPriceDrop->value());//calculateGroupValues(); calculateProfit( ui->editFinalPrice->text() ); //qDebug()<<"There are "<<groupInfo.count<<" items in group. The cost is:"<<groupInfo.cost<<", The price is:"<<groupInfo.price<<" And is available="<<groupInfo.isAvailable; delete myDb; } void ProductEditor::removeItem() { groupInfo.count = 0; groupInfo.cost = 0; groupInfo.price = 0; groupInfo.tax = 0; groupInfo.taxMoney = 0; if (ui->groupView->currentRow() != -1 ){ //get selected item from group view int row = ui->groupView->currentRow(); QTableWidgetItem *item = ui->groupView->item(row, 1); QString name = item->data(Qt::DisplayRole).toString(); Azahar *myDb = new Azahar; myDb->setDatabase(db); //get code from db qulonglong code = myDb->getProductCode(name); ProductInfo pInfo = groupInfo.productsList.take(code); //insert it later... double qty = 0; qty = pInfo.qtyOnList; //from hash | must be the same on groupView if (qty>1) { //qty--; if ( pInfo.units == 1 ) qty -= int(ui->editGroupQty->value()); //increment it (PIECES) else qty -= ui->editGroupQty->value(); //increment it (OTHER MEASURES) pInfo.qtyOnList = qty; //reinsert it again groupInfo.productsList.insert(code, pInfo); } delete myDb; } //there is something selected //reload groupView updatePriceDrop(ui->editGroupPriceDrop->value());//calculateGroupValues(); calculateProfit( ui->editFinalPrice->text() ); //qDebug()<<"There are "<<groupInfo.count<<" items in group. The cost is:"<<groupInfo.cost<<", The price is:"<<groupInfo.price<<" And is available="<<groupInfo.isAvailable; } void ProductEditor::itemDoubleClicked(QTableWidgetItem* item) { groupInfo.count = 0; groupInfo.cost = 0; groupInfo.price = 0; groupInfo.tax = 0; groupInfo.taxMoney = 0; int row = item->row(); QTableWidgetItem *itm = ui->groupView->item(row, 1); QString name = itm->data(Qt::DisplayRole).toString(); Azahar *myDb = new Azahar; myDb->setDatabase(db); //get code from db qulonglong code = myDb->getProductCode(name); ProductInfo pInfo = groupInfo.productsList.take(code); //insert it later... double qty = 0; qty = pInfo.qtyOnList+1; //from hash | must be the same on groupView //modify pInfo pInfo.qtyOnList = qty; //increment it one by one //reinsert it to the hash groupInfo.productsList.insert(code, pInfo); //reload groupView updatePriceDrop(ui->editGroupPriceDrop->value()); //calculateGroupValues(); calculateProfit( ui->editFinalPrice->text() ); delete myDb; } QString ProductEditor::getGroupElementsStr() { QStringList list; foreach(ProductInfo info, groupInfo.productsList) { list.append(QString::number(info.code)+"/"+QString::number(info.qtyOnList)); } return list.join(","); } bool ProductEditor::isGroup() { bool result=false; if (groupInfo.count>0 && ui->chIsAGroup->isChecked()) result = true; return result; } bool ProductEditor::isRaw() { return ui->chIsARaw->isChecked(); } bool ProductEditor::isNotDiscountable() { return ui->chNotDiscountable->isChecked(); } bool ProductEditor::hasUnlimitedStock() { return ui->chUnlimitedStock->isChecked(); } GroupInfo ProductEditor::getGroupHash() { return groupInfo; } void ProductEditor::toggleGroup(bool checked) { if (checked) { groupPanel->showPanel(); ui->btnStockCorrect->setDisabled(true); ui->chIsARaw->setDisabled(true); ui->chIsARaw->setChecked(false); ui->btnShowGroup->setEnabled(true); m_model->setFilter("products.isAGroup=0 AND products.isARawProduct=0"); m_model->select(); if (ui->editGroupPriceDrop->value() <= 0) { ui->editGroupPriceDrop->setValue(10); groupInfo.priceDrop = 10; } } else { groupPanel->hidePanel(); ui->btnStockCorrect->setEnabled(true); ui->btnShowGroup->setDisabled(true); ui->chIsARaw->setEnabled(true); m_model->setFilter(""); m_model->select(); } ui->editTax->setReadOnly(checked); ui->editExtraTaxes->setReadOnly(checked); ui->editCost->setReadOnly(checked); ui->editFinalPrice->setReadOnly(checked); ui->groupBox->setDisabled(checked); } void ProductEditor::toggleRaw(bool checked) { if (checked){ ui->chIsAGroup->setDisabled(true); ui->chIsAGroup->setChecked(false); ui->btnShowGroup->setDisabled(true); } else { ui->chIsAGroup->setEnabled(true); } } void ProductEditor::setIsAGroup(bool value) { ui->chIsAGroup->setChecked(value); ui->btnShowGroup->setEnabled(value); ui->btnStockCorrect->setDisabled(value); //dont allow grouped products to make stock correction ui->editTax->setReadOnly(value); ui->editExtraTaxes->setReadOnly(value); ui->editCost->setReadOnly(value); ui->editFinalPrice->setReadOnly(value); ui->groupBox->setDisabled(value); } void ProductEditor::setIsARaw(bool value) { ui->chIsARaw->setChecked(value); } void ProductEditor::setUnlimitedStock(bool value) { ui->chUnlimitedStock->setChecked(value); //disable/enable stock correct button ui->btnStockCorrect->setEnabled(!value); qDebug()<<"setUnlimitedStock:"<<value; } void ProductEditor::setNotDiscountable(bool value) { ui->chNotDiscountable->setChecked(value); qDebug()<<"setNotDiscountable:"<<value; } void ProductEditor::setGroupElements(ProductInfo pi) { if (!ui->chIsAGroup->isChecked()) return; Azahar *myDb = new Azahar; myDb->setDatabase(db); groupInfo = myDb->getGroupPriceAndTax(pi); foreach(ProductInfo info, groupInfo.productsList) { //insert it to the groupView int rowCount = ui->groupView->rowCount(); ui->groupView->insertRow(rowCount); ui->groupView->setItem(rowCount, 0, new QTableWidgetItem(QString::number(info.qtyOnList))); ui->groupView->setItem(rowCount, 1, new QTableWidgetItem(info.desc)); } ui->groupView->resizeRowsToContents(); ui->groupView->resizeColumnsToContents(); delete myDb; ui->editTax->setText(QString::number(groupInfo.tax)); ui->editCost->setText(QString::number(groupInfo.cost)); ui->editFinalPrice->setText(QString::number(groupInfo.price)); ui->editExtraTaxes->setText("0.0"); ui->lblGPrice->setText(KGlobal::locale()->formatMoney(groupInfo.price, QString(), 2)); ui->editGroupPriceDrop->setValue(groupInfo.priceDrop); } void ProductEditor::updatePriceDrop(double value) { //NOTE: When changing the pricedrop and cancelling the product editor (not saving product changes) the pricedrop IS CHANGED ANYWAY // This is because we are updating price drop on change and not until the product is saved (dialog OK) for re-calculateGroupValues // So, the cancel button on the product will not prevent or UNDO these changes. // TODO: Add this note to the manuals. /// TODO: Make a backup of the priceDrop, and if cancelled, restore the backup to the db from the caller (outside this class) //first save on db... Azahar *myDb = new Azahar; myDb->setDatabase(db); myDb->updateGroupPriceDrop(getCode(), value); myDb->updateGroupElements(getCode(), getGroupElementsStr()); ProductInfo info = myDb->getProductInfo( QString::number( getCode() ) ); /// NOTE: this info is for the method below.. GroupInfo giTemp = myDb->getGroupPriceAndTax(info); delete myDb; //if there is a new product, it will not be updated because it does not exists on db yet... so fix the groupPrice drop if (info.code == 0 ) { groupInfo.priceDrop = ui->editGroupPriceDrop->value(); calculateGroupValues(); } else { //then update prices on UI groupInfo = giTemp; ui->editCost->setText(QString::number(groupInfo.cost)); ui->editFinalPrice->setText(QString::number(groupInfo.price)); ui->editExtraTaxes->setText("0.0"); ui->editTax->setText(QString::number(groupInfo.tax)); ui->lblGPrice->setText(KGlobal::locale()->formatMoney(groupInfo.price, QString(), 2)); //update listview while (ui->groupView->rowCount() > 0) ui->groupView->removeRow(0); foreach(ProductInfo info, groupInfo.productsList) { int rowCount = ui->groupView->rowCount(); ui->groupView->insertRow(rowCount); ui->groupView->setItem(rowCount, 0, new QTableWidgetItem(QString::number(info.qtyOnList))); ui->groupView->setItem(rowCount, 1, new QTableWidgetItem(info.desc)); } ui->groupView->resizeRowsToContents(); ui->groupView->resizeColumnsToContents(); } } void ProductEditor::calculateGroupValues() { groupInfo.count = 0; groupInfo.cost = 0; groupInfo.price = 0; groupInfo.tax = 0; groupInfo.taxMoney = 0; while (ui->groupView->rowCount() > 0) ui->groupView->removeRow(0); foreach(ProductInfo info, groupInfo.productsList) { //update groupInfo groupInfo.count += info.qtyOnList; groupInfo.cost += info.cost*info.qtyOnList; if (ui->chRise->isChecked()) { groupInfo.price += (info.price +info.price*(groupInfo.priceDrop/100)) * info.qtyOnList; //info.price*info.qtyOnList; } else { groupInfo.price += (info.price -info.price*(groupInfo.priceDrop/100)) * info.qtyOnList; //info.price*info.qtyOnList; } groupInfo.taxMoney += info.totaltax*info.qtyOnList; bool yes = false; if (info.stockqty >= info.qtyOnList ) yes = true; groupInfo.isAvailable = (groupInfo.isAvailable && yes ); //insert it to the groupView int rowCount = ui->groupView->rowCount(); ui->groupView->insertRow(rowCount); ui->groupView->setItem(rowCount, 0, new QTableWidgetItem(QString::number(info.qtyOnList))); ui->groupView->setItem(rowCount, 1, new QTableWidgetItem(info.desc)); } ui->groupView->resizeRowsToContents(); ui->groupView->resizeColumnsToContents(); //update cost and price on the form ui->editCost->setText(QString::number(groupInfo.cost)); ui->editFinalPrice->setText(QString::number(groupInfo.price)); ui->editExtraTaxes->setText("0.0"); //calculate compound tax for the group. groupInfo.tax = 0; foreach(ProductInfo info, groupInfo.productsList) { groupInfo.tax += (info.totaltax*info.qtyOnList/groupInfo.price)*100; // totalTaxMoney = price*(taxPercentage/100) qDebug()<<" <Calculating Values> qtyOnList:"<<info.qtyOnList<<" tax money for product: "<<info.totaltax<<" group price:"<<groupInfo.price<<" taxMoney for group:"<<groupInfo.taxMoney<<" tax % for group:"<< groupInfo.tax; } ui->editTax->setText(QString::number(groupInfo.tax)); ui->lblGPrice->setText(KGlobal::locale()->formatMoney(groupInfo.price, QString(), 2)); } double ProductEditor::getGRoupStockMax() { return 1; // stockqty on grouped products will not be stored, only check for contents availability } qulonglong ProductEditor::getNextCode() { qulonglong r=0; Azahar *myDb = new Azahar; myDb->setDatabase(db); r = myDb->getNextProductCode() + 1; qDebug()<<__FUNCTION__<<" next code:"<<r; return r; } void ProductEditor::verifyAlphacodeDuplicates() { QString strAc = ui->editAlphacode->text(); if (strAc.isEmpty()) strAc="-1"; Azahar *myDb = new Azahar; myDb->setDatabase(db); qulonglong rcode = myDb->getProductCodeFromAlphacode(strAc); if (rcode > 0) { errorAlphacode->showTip(i18n("Alpha Code %1 already exists.", strAc),3000); enableButtonOk( false ); qDebug()<<"Duplicate alphacode!"; } else { enableButtonOk( true ); } delete myDb; } void ProductEditor::verifyVendorcodeDuplicates() { QString strVc = ui->editVendorcode->text(); if (strVc.isEmpty()) strVc="-1"; Azahar *myDb = new Azahar; myDb->setDatabase(db); qulonglong rcode = myDb->getProductCodeFromVendorcode(strVc); if (rcode > 0) { errorVendorcode->showTip(i18n("Vendor Code %1 already exists.", strVc),3000); enableButtonOk( false ); qDebug()<<"Duplicate vendor code!"; } else { enableButtonOk( true ); } delete myDb; } void ProductEditor::modifyDepartment() { //When a department is changed, we must filter categories according. QString depText = ui->departmentsCombo->currentText(); Azahar *myDb = new Azahar; myDb->setDatabase(db); //get categories.. qulonglong parentId = myDb->getDepartmentId( depText ); QStringList catList = myDb->getCategoriesList( parentId ); ui->categoriesCombo->clear(); ui->categoriesCombo->addItems( catList ); qDebug()<<"CAT LIST for "<<depText<<" :"<<catList; delete myDb; } void ProductEditor::modifyCategory() { //When a category is changed, we must filter subcategories according. QString catText = ui->categoriesCombo->currentText(); Azahar *myDb = new Azahar; myDb->setDatabase(db); //get subcategories' children qulonglong parentId = myDb->getCategoryId( catText ); QStringList subcatList = myDb->getSubCategoriesList( parentId ); ui->subcategoriesCombo->clear(); ui->subcategoriesCombo->addItems( subcatList ); qDebug()<<"SUBCAT LIST for ("<<parentId<<") "<<catText<<" :"<<subcatList; delete myDb; } void ProductEditor::createNewSubcategory() { bool ok=false; QString cat = QInputDialog::getText(this, i18n("New subcategory"), i18n("Enter the new subcategory:"), QLineEdit::Normal, "", &ok ); if (ok && !cat.isEmpty()) { Azahar *myDb = new Azahar; myDb->setDatabase(db); if (!myDb->insertSubCategory(cat)) qDebug()<<"Error:"<<myDb->lastError(); //modifyCategory(); //BUG:It is weird that this does not appends the new item; it should do it. ui->subcategoriesCombo->addItems( QStringList(cat) ); //WORK AROUND setSubCategory(cat); //NOTE: Hey, the subcategory here belongs to a category.. so we must insert the m2m relation! qulonglong scId = myDb->getSubCategoryId(cat); qulonglong cId = myDb->getCategoryId( ui->categoriesCombo->currentText() ); qDebug()<<cId<<"-->"<<scId<<" | "<<cat<<"-->"<<ui->categoriesCombo->currentText(); if (!myDb->insertM2MCategorySubcategory(cId, scId)) qDebug()<<"ERROR:"<<myDb->lastError(); delete myDb; } } void ProductEditor::createNewCategory() { //launch dialog to ask for the new child. Using this same dialog. SubcategoryEditor *scEditor = new SubcategoryEditor(this); scEditor->setDb(db); Azahar *myDb = new Azahar; myDb->setDatabase(db); QStringList list = myDb->getSubCategoriesList(); scEditor->setCatList( myDb->getCategoriesList() ); scEditor->setScatList( list ); scEditor->populateList( list ); scEditor->setDialogType(2); //category = 2 scEditor->setLabelForName(i18n("New category:")); scEditor->setLabelForList(i18n("Select the child subcategories for this category:")); if ( scEditor->exec() ) { QString text = scEditor->getName(); QStringList children = scEditor->getChildren(); qDebug()<<text<<" CHILDREN:"<<children; //Create the category if (!myDb->insertCategory(text)) { qDebug()<<"Error:"<<myDb->lastError(); delete myDb; return; } qulonglong cId = myDb->getCategoryId(text); //create the m2m relations for the new category->subcategory. foreach(QString cat, children) { //get subcategory id qulonglong scId = myDb->getSubCategoryId(cat); //create the link [category] --> [subcategory] myDb->insertM2MCategorySubcategory(cId, scId); } //reload categories combo //modifyDepartment();//BUG:It is weird that this does not appends the new item; it should do it. ui->categoriesCombo->addItems( QStringList(text) ); //WORK AROUND setCategory(text); //set the newly created category... } } void ProductEditor::createNewDepartment() { //launch dialog to ask for the new child. Using this same dialog. SubcategoryEditor *scEditor = new SubcategoryEditor(this); scEditor->setDb(db); Azahar *myDb = new Azahar; myDb->setDatabase(db); QStringList list = myDb->getCategoriesList(); scEditor->setCatList( list ); scEditor->setScatList( myDb->getSubCategoriesList() ); scEditor->populateList( list ); scEditor->setDialogType(1); //department = 1 scEditor->setLabelForName(i18n("New department:")); scEditor->setLabelForList(i18n("Select the child categories for this department:")); if ( scEditor->exec() ) { QString text = scEditor->getName(); QStringList children = scEditor->getChildren(); qDebug()<<text<<" CHILDREN:"<<children; //Create the department if (!myDb->insertDepartment(text)) { qDebug()<<"Error:"<<myDb->lastError(); delete myDb; return; } qulonglong depId = myDb->getDepartmentId(text); //create the m2m relations for the new department->category. foreach(QString cat, children) { //get category id qulonglong cId = myDb->getCategoryId(cat); //create the link [category] --> [subcategory] myDb->insertM2MDepartmentCategory(depId, cId); } //reload departments combo populateDepartmentsCombo(); //ui->DepartmentsCombo->addItems( QStringList(text) ); //WORK AROUND setDepartment(text); //set the newly created category... } } void ProductEditor::createNewMeasure() { bool ok=false; QString meas = QInputDialog::getText(this, i18n("New Weight or Measure"), i18n("Enter the new weight or measure to insert:"), QLineEdit::Normal, "", &ok ); if (ok && !meas.isEmpty()) { Azahar *myDb = new Azahar; if (!db.isOpen()) db.open(); myDb->setDatabase(db); if (!myDb->insertMeasure(meas)) qDebug()<<"Error:"<<myDb->lastError(); populateMeasuresCombo(); setMeasure(meas); delete myDb; } } #include "producteditor.moc" void ProductEditorUI::on_chRise_clicked(bool checked) { }
44,410
C++
.cpp
1,128
34.935284
224
0.679717
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
752,835
print-dev.h
hiramvillarreal_iotpos/printing/print-dev.h
/************************************************************************** * Copyright (C) 2013-2015 by Hiram R. Villarreal * * hiramvillarreal.ap@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #ifndef PRINT_DEV_H #define PRINT_DEV_H /** * This class is for printing on printers supporting the ports /dev/XXX * Accessing them trough qfile. * * @author Miguel Chavez Gamboa <miguel@iotpospos.org> * @version 0.1 */ class QString; class PrintDEV { public: static bool printSmallBalance(const QString &dev, const QString &codec, const QString &lines); static bool printSmallTicket(const QString &dev, const QString &codec, const QString &lines); }; #endif
1,925
C++
.h
35
53.571429
98
0.504772
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,836
print-cups.h
hiramvillarreal_iotpos/printing/print-cups.h
/************************************************************************** * Copyright © 2007-2010 by Miguel Chavez Gamboa * * hiramvillarreal.ap@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #ifndef PRINT_CUPS_H #define PRINT_CUPS_H #include "../src/structs.h" /** * This class is for printing on printers with cups driver installed * Accessing them trough cups. * * @author Miguel Chavez Gamboa <miguel@iotpospos.org> * @version 0.2 */ class QString; class PrintCUPS { public: static bool printSmallBalance(const PrintBalanceInfo &pbInfo, QPrinter &printer); //NOTE Apr 14 2011: Fixed page/font size. static bool printSmallTicket(const PrintTicketInfo &ptInfo, QPrinter &printer);//NOTE Apr 14 2011: Fixed page/font size. static bool printBigTicket(const PrintTicketInfo &ptInfo, QPrinter &printer); static bool printSmallEndOfDay(const PrintEndOfDayInfo &pdInfo, QPrinter &printer);//NOTE Apr 14 2011: Fixed page/font size. static bool printBigEndOfDay(const PrintEndOfDayInfo &pdInfo, QPrinter &printer); static bool printSmallLowStockReport(const PrintLowStockInfo &plInfo, QPrinter &printer); static bool printBigLowStockReport(const PrintLowStockInfo &plInfo, QPrinter &printer); static bool printSmallSOTicket(const PrintTicketInfo &ptInfo, QPrinter &printer); //NOTE Apr 14 2011: Fixed page/font size. //static bool printSmallReservationTicket(const PrintTicketInfo &ptInfo, QPrinter &printer); //NOTE:WHAT ABOUT THIS! }; #endif
2,759
C++
.h
43
61.604651
128
0.591128
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,837
azahar.h
hiramvillarreal_iotpos/dataAccess/azahar.h
/*************************************************************************** * Copyright © 2007-2012 by Miguel Chavez Gamboa * * hiramvillarreal.ap@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #ifndef AZAHAR_H #define AZAHAR_H #include <QtSql> #include <QObject> #include <QHash> #include "../src/structs.h" #include "../src/enums.h" enum AzaharRTypes {rtPercentage=1001, rtMoney=1002}; class QString; /** * This class makes all database access. * * @short Database access class * @author Miguel Chavez Gamboa <miguel.chavez.gamboa@gmail.com> * @version 0.9 */ class Azahar : public QObject { Q_OBJECT //NOTE: This also gives the extra function of self destroying when parent is destroyed ? it has no parent private: QSqlDatabase db; QString errorStr; void setError(QString err); QString m_mainClient; public: Azahar(QWidget * parent = 0); ~ Azahar(); bool isConnected(); QString lastError(); void initDatabase(QString user, QString server, QString password, QString dbname); void setDatabase(const QSqlDatabase& database); // PRODUCTS ProductInfo getProductInfo(const QString &code, const bool &notConsiderDiscounts = false); //the 2nd parameter is to get the taxes for the group (not considering discounts) qulonglong getProductOfferCode(qulonglong code); qulonglong getProductCode(QString text); qulonglong getProductCodeFromAlphacode(QString text); qulonglong getProductCodeFromVendorcode(QString text); QList<qulonglong> getProductsCode(QString regExpName); QStringList getProductsList(); bool insertProduct(ProductInfo info); bool updateProduct(ProductInfo info, qulonglong oldcode); bool decrementProductStock(qulonglong code, double qty, QDate date); bool decrementGroupStock(qulonglong code, double qty, QDate date); bool incrementGroupStock(qulonglong code, double qty); bool incrementProductStock(qulonglong code, double qty); bool deleteProduct(qulonglong code); double getProductDiscount(qulonglong code, bool isGroup=false); //returns the discount percentage! QList<pieProdInfo> getTop5SoldProducts(); double getTopFiveMaximum(); QList<pieProdInfo> getAlmostSoldOutProducts(int max); double getAlmostSoldOutMaximum(int max); QList<ProductInfo> getSoldOutProducts(); QList<ProductInfo> getLowStockProducts(double min); QList<ProductInfo> getAllProducts(); double getProductStockQty(qulonglong code); qulonglong getLastProviderId(qulonglong code); bool updateProductLastProviderId(qulonglong code, qulonglong provId); QList<ProductInfo> getGroupProductsList(qulonglong id, bool notConsiderDiscounts = false); /* DEPRECATED double getGroupAverageTax(qulonglong id); DEPRECATED double getGroupTotalTax(qulonglong id); */ GroupInfo getGroupPriceAndTax(ProductInfo pi); QString getProductGroupElementsStr(qulonglong id); void updateGroupPriceDrop(qulonglong code, double pd); void updateGroupElements(qulonglong code, QString elementsStr); qulonglong getNextProductCode(); //PRODUCT STOCK CORRECTION bool correctStock(qulonglong pcode, double oldStockQty, double newStockQty, const QString &reason ); //bundles -- Same product (Simple bundle => 2x 1, 3x0.8 ..) QList<BundleInfo> getBundleInfo(qulonglong productId); BundleInfo getMaxBundledForProduct(qulonglong pId); double getBundlePriceFor(qulonglong pId); //DEPARTMENTS QHash<QString, int> getDepartmentsHash(); QStringList getDepartmentsList(); qulonglong getDepartmentId(QString texto); QString getDepartmentStr(qulonglong id); bool insertDepartment(QString text); bool deleteDepartment(qulonglong id); bool updateDepartment(qulonglong id, QString t); //to rename a department. //m2m bool m2mDepartmentCategoryExists(qulonglong d, qulonglong c); bool insertM2MDepartmentCategory(qulonglong depId, qulonglong catId); bool m2mDepartmentCategoryRemove(qulonglong d, qulonglong c); //CATEGORIES QHash<QString, int> getCategoriesHash(); QStringList getCategoriesList(); QStringList getCategoriesList(const qulonglong parent); qulonglong getCategoryId(QString texto); QString getCategoryStr(qulonglong id); bool insertCategory(QString text); bool updateCategory(qulonglong id, QString t); //to rename a category. bool deleteCategory(qulonglong id); //m2m bool insertM2MCategorySubcategory(qulonglong catId, qulonglong subcatId); bool m2mCategorySubcategoryExists(qulonglong c, qulonglong s); bool m2mCategorySubcategoryRemove(qulonglong c, qulonglong sc); //SUBCATEGORIES QHash<QString, int> getSubCategoriesHash(); QStringList getSubCategoriesList(); QStringList getSubCategoriesList(const qulonglong parent); qulonglong getSubCategoryId(QString texto); QString getSubCategoryStr(qulonglong id); bool insertSubCategory(QString text); bool deleteSubCategory(qulonglong id); //MEASURES QStringList getMeasuresList(); qulonglong getMeasureId(QString texto); QString getMeasureStr(qulonglong id); bool insertMeasure(QString text); bool deleteMeasure(qulonglong id); //OFFERS bool createOffer(OfferInfo info); bool deleteOffer(qlonglong id); QString getOffersFilterWithText(QString text); //get all products with desc=text as a regexp that has discounts. bool moveOffer(qulonglong oldp, qulonglong newp); //USERS bool updateUser(UserInfo info); QString getUserName(QString username); //gets the user name from username QString getUserName(qulonglong id); unsigned int getUserId(QString uname); unsigned int getUserIdFromName(QString uname); QHash<QString,UserInfo> getUsersHash(); QStringList getUsersList(); bool insertUser(UserInfo info); int getUserRole(const qulonglong &userid); UserInfo getUserInfo(const qulonglong &userid); bool deleteUser(qulonglong id); //CLIENTS bool insertClient(ClientInfo info); bool updateClient(ClientInfo info); bool incrementClientPoints(qulonglong id, qulonglong points); bool decrementClientPoints(qulonglong id, qulonglong points); ClientInfo getClientInfo(qulonglong clientId); ClientInfo getClientInfo(QString clientCode); QHash<QString, ClientInfo> getClientsHash(); QStringList getClientsList(); QString getMainClient(); unsigned int getClientId(QString uname); bool deleteClient(qulonglong id); //TRANSACTIONS TransactionInfo getTransactionInfo(qulonglong id); qulonglong insertTransaction(TransactionInfo info); //QList<ProductInfo> getTransactionGroupsList(qulonglong tid); QList<TransactionInfo> getDayTransactions(int terminal); QList<TransactionInfo> getDayTransactions(); AmountAndProfitInfo getDaySalesAndProfit(int terminal); AmountAndProfitInfo getDaySalesAndProfit(); QList<TransactionInfo> getMonthTransactionsForPie(); QList<TransactionInfo> getMonthTransactions(); AmountAndProfitInfo getMonthSalesAndProfit(); ProfitRange getMonthProfitRange(); ProfitRange getMonthSalesRange(); bool updateTransaction(TransactionInfo info); bool cancelTransaction(qulonglong id, bool inProgress); bool deleteTransaction(qulonglong id); bool deleteEmptyTransactions(); QList<TransactionInfo> getLastTransactions(int pageNumber=1,int numItems=20,QDate beforeDate=QDate::currentDate ()); QList<TransactionInfo> getTransactionsPerDay(int pageNumber=1,int numItems=20,QDate beforeDate=QDate::currentDate ()); qulonglong getEmptyTransactionId(); double getTransactionDiscMoney(qulonglong id); bool setTransactionStatus(qulonglong trId, TransactionState state); // TRANSACTIONITEMS bool insertTransactionItem(TransactionItemInfo info); bool deleteAllTransactionItem(qulonglong id); QList<TransactionItemInfo> getTransactionItems(qulonglong id); //BALANCES qulonglong insertBalance(BalanceInfo info); bool updateBalance(BalanceInfo info); BalanceInfo getBalanceInfo(qulonglong id); //CASHOUTS qulonglong insertCashFlow(CashFlowInfo info); QList<CashFlowInfo> getCashFlowInfoList(const QList<qulonglong> &idList); QList<CashFlowInfo> getCashFlowInfoList(const QDateTime &start, const QDateTime &end); //CardTypes QString getCardTypeStr(qulonglong type); qulonglong getCardTypeId(QString type); QStringList getCardTypes(); QHash<QString,int> getCardTypesHash(); //PayTypes QString getPayTypeStr(qulonglong type); qulonglong getPayTypeId(QString type); //LOGS bool insertLog(const qulonglong &userid, const QDate &date, const QTime &time, const QString actionStr); //new config way - for cross binary access. bool getConfigFirstRun(); bool getConfigTaxIsIncludedInPrice(); void cleanConfigFirstRun(); void setConfigTaxIsIncludedInPrice(bool option); QPixmap getConfigStoreLogo(); QString getConfigStoreName(); QString getConfigStoreAddress(); QString getConfigStorePhone(); bool getConfigSmallPrint(); bool getConfigLogoOnTop(); bool getConfigUseCUPS(); QString getConfigDbVersion(); //NEW: Aug 31 2011. void setConfigStoreLogo(const QByteArray &baPhoto); void setConfigStoreName(const QString &str); void setConfigStoreAddress(const QString &str); void setConfigStorePhone(const QString &str); void setConfigSmallPrint(bool yes); void setConfigUseCUPS(bool yes); void setConfigLogoOnTop(bool yes); //Special Orders void specialOrderSetStatus(qulonglong id, int status); void soTicketSetStatus(qulonglong ticketId, int status); qulonglong insertSpecialOrder(SpecialOrderInfo info); bool updateSpecialOrder(SpecialOrderInfo info); bool decrementSOStock(qulonglong id, double qty, QDate date); bool deleteSpecialOrder(qulonglong id); SpecialOrderInfo getSpecialOrderInfo(qulonglong id); QList<ProductInfo> getSpecialOrderProductsList(qulonglong id); QString getSpecialOrderProductsStr(qulonglong id); QList<SpecialOrderInfo> getAllSOforSale(qulonglong saleId); QList<SpecialOrderInfo> getAllReadySOforSale(qulonglong saleId); int getReadySOCountforSale(qulonglong saleId); QString getSONotes(qulonglong id); QStringList getStatusList(); QStringList getStatusListExceptDelivered(); int getStatusId(QString texto); double getSpecialOrderAverageTax(qulonglong id, AzaharRTypes returnType= rtPercentage); double getSpecialOrderAverageDiscount(qulonglong id); int getSpecialOrderNonDiscountables(qulonglong id); //Reservations qulonglong insertReservation(ReservationInfo info); bool setReservationStatus(qulonglong id, reservationState state); double getReservationTotalAmount(qulonglong id); double getReservationPayment(qulonglong id); bool setTransactionReservationStatus(const qulonglong &trId); ReservationInfo getReservationInfo(const qulonglong &id); ReservationInfo getReservationInfoFromTr(const qulonglong &trId); bool addReservationPayment( const qulonglong &rId, const double &amount ); QList<ReservationPayment> getReservationPayments( const qulonglong &rId ); bool setReservationPayment(const qulonglong &id, const double &amount ); //Random Msgs QString getRandomMessage(QList<qulonglong> &excluded, const int &season); //NOTE:We will modify excluded list.. SO do not make const the List. void randomMsgIncrementCount(qulonglong id); bool insertRandomMessage(const QString &msg, const int &season); //Currencies CurrencyInfo getCurrency(const qulonglong &id); CurrencyInfo getCurrency(const QString &name); QList<CurrencyInfo> getCurrencyList(); bool insertCurrency(const QString name, const double &factor); bool deleteCurrency(const qulonglong &cid); //Credits and its history CreditInfo getCreditInfoForClient(const qulonglong &clientId, const bool &create=true); //by default it creates a new credit record if no one found for the customer. QList<CreditHistoryInfo> getCreditHistoryForClient(const qulonglong &clientId, const int &lastDays=0); qulonglong insertCredit(const CreditInfo &info); bool updateCredit(const CreditInfo &info); qulonglong insertCreditHistory(const CreditHistoryInfo &info); }; #endif
14,795
C++
.h
272
49.617647
177
0.686493
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,838
mibitnotifier.h
hiramvillarreal_iotpos/mibitWidgets/mibitnotifier.h
/*************************************************************************** * Copyright (C) 2009 by Miguel Chavez Gamboa * * hiramvillarreal.ap@gmail.com * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #ifndef MIBITNOTIFIER_H #define MIBITNOTIFIER_H #include <QSvgWidget> class QTimeLine; class QString; class QHBoxLayout; class QLabel; class QPixmap; /** * This class is used to display animated notifications appering on parent * top or bottom. Are svg themed and borderless. * */ enum sizes { max_H=200, max_W=400, min_W=300, min_H=100 }; class MibitNotifier : public QSvgWidget { Q_OBJECT public: MibitNotifier(QWidget *parent = 0, const QString &file = 0, const QPixmap &icon = 0, const bool &onTop= true); ~MibitNotifier(); void showNotification( const QString &msg = 0, const int &timeToLive = 0); //timeToLive = 0 : not auto hide it. void setOnBottom(const bool &sOnBottom = true); void setSVG(const QString &file); void setIcon(const QPixmap &icon); void setMessage(const QString &msg); void setTextColor(const QString &color); void setMaxHeight(const int &m) { setMaximumHeight(m); maxHeight = m; } void setMaxWidth(const int &m) { setMaximumWidth(m); maxWidth = m; } void setSize( const int &w, const int &h ) { setMaxHeight(h); setMaxWidth(w); } private: QTimeLine *timeLine; QLabel *message; QHBoxLayout *hLayout; QLabel *img; QWidget *m_parent; QString m_fileName; bool m_canClose; bool m_onTop; int maxHeight; int maxWidth; int animRate; private slots: void animate(const int &step); void hideDialog(); void hideOnUserRequest(); void onAnimationFinished(); protected: void mousePressEvent ( QMouseEvent * event ); }; #endif // MIBITNOTIFIER_H
3,046
C++
.h
69
41.115942
115
0.574891
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,839
mibitlineedit.h
hiramvillarreal_iotpos/mibitWidgets/mibitlineedit.h
/*************************************************************************** * Copyright (C) 2009 by Miguel Chavez Gamboa * * hiramvillarreal.ap@gmail.com * * * * This is based on the KLineEdit class * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #ifndef MIBITLINEEDIT_H #define MIBITLINEEDIT_H #include <QLineEdit> class QTimer; class MibitLineEdit : public QLineEdit { Q_OBJECT public: explicit MibitLineEdit( const QString &string, QWidget *parent = 0 ); explicit MibitLineEdit( QWidget *parent = 0 ); virtual ~MibitLineEdit(); /** * This makes the line edit display a grayed-out hinting text as long as * the user didn't enter any text. It is often used as indication about * the purpose of the line edit. */ void setEmptyMessage( const QString &msg ); /** * @return the message set with setEmptyMessage */ QString getEmptyMessage() const; /** * sets background color to indicate an error on input. */ void setError( const QString& msg ); /** * sets automatic clear of errors */ void setAutoClearError( const bool& state ); protected: virtual void paintEvent( QPaintEvent *ev ); virtual void focusInEvent( QFocusEvent *ev ); virtual void focusOutEvent( QFocusEvent *ev ); virtual void keyPressEvent( QKeyEvent * event ); private: QString emptyMessage; bool drawEmptyMsg; bool drawError; bool autoClear; int actualColor; QTimer *timer; QTimer *shakeTimer; int shakeTimeToLive; bool par; unsigned int parTimes; private slots: void onTextChange(const QString &text); void stepColors(); void shakeIt(); public slots: void shake(); void clearError(); signals: void plusKeyPressed(); }; #endif // MibitLineEdit_H
3,203
C++
.h
77
37.74026
77
0.542068
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,840
mibittip.h
hiramvillarreal_iotpos/mibitWidgets/mibittip.h
/*************************************************************************** * Copyright (C) 2009 by Miguel Chavez Gamboa * * hiramvillarreal.ap@gmail.com * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #ifndef MIBITTIP_H #define MIBITTIP_H #include <QSvgWidget> class QTimeLine; class QVBoxLayout; class QSize; class QString; class QLabel; class QPixmap; enum TipPosition {tpBelow, tpAbove}; /** * This class is used to display animated messages * growing or shrinking when showing/hiding. * * The concept is based on the idea of providing a less * intrusive message when the user needs some little information. * The concept is sometimes refered as "No dialogs on dialogs". * * It loads a file in SVG format and render it as the skin. * As it is an SVG, it can be scaled to any size. * * It is resized according to its parter, and displayed * horizontally centered and vertically positioned below * or above its partner. * * This was designed for iotposPOS project. * **/ class MibitTip : public QSvgWidget { Q_OBJECT public: explicit MibitTip( QWidget *parent = 0, QWidget *partner = 0, const QString &file = 0, const QPixmap &icon = 0, const TipPosition &drawOn = tpBelow ); virtual ~MibitTip(); /** * This method shows a tip frame centered horizontally and on bottom of its parter. * It should be parented on a bigger widget to be visible (for example the main window) * and also must be the same parent for the parter (must be on the same container). * Its partner is the widget where the tip frame will be shown on. * */ void showTip( const QString &msg, const int ttl ); void setSVG( const QString &file ); void setIcon(const QPixmap &icon ); void setMaxHeight(int h) { maxHeight = h; } void setMaxWidth(int w) { maxWidth = w; } void setSize(const int &w, const int &h) { setMaxHeight(h); setMaxWidth(w); } private: QWidget *m_parent; QWidget *m_partner; QTimeLine *timeLine; QLabel *text; QVBoxLayout *layout; QLabel *img; TipPosition m_tipPosition; int maxHeight; int maxWidth; QString fileName; bool closedByUser; int timeToLive; protected: void mousePressEvent ( QMouseEvent * event ); private slots: void morph(int newSize); void autoHide(); }; #endif // MIBITTIP_H
3,729
C++
.h
90
37.1
92
0.579034
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,841
mibitpassworddlg.h
hiramvillarreal_iotpos/mibitWidgets/mibitpassworddlg.h
/*************************************************************************** * Copyright (C) 2009 by Miguel Chavez Gamboa * * hiramvillarreal.ap@gmail.com * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #ifndef MIBITPASSWORDDLG_H #define MIBITPASSWORDDLG_H #include <QSvgWidget> #include <QLineEdit> class QTimeLine; class QString; class QHBoxLayout; class QVBoxLayout; class QLabel; class QPixmap; class QPushButton; /** * This class is used to display animated dialogs appering on screen's * top or middle. Are svg themed and borderless. * It can also shake it or wave it to take user's attention. * * The animation types are four: * atGrowCenterV: This makes the dialog appear growing from the center in the Y axe. * atGrowCenterH: This makes the dialog appear growing from the center in the X axe. * atSlideDown: This makes the dialog appear sliding down from the top of its parent. * atSlideUp: This makes the dialog appear sliding up from the bottom of its parent. * * */ enum AnimationTypeP { atpGrowCenterV=1, atpGrowCenterH=2, atpSlideDown=3, atpSlideUp=4 }; enum SizesP { pmaxH=300, pmaxW=400 }; class MibitPasswordDialog : public QSvgWidget { Q_OBJECT public: MibitPasswordDialog(QWidget *parent = 0, const QString &msg = 0, const QString &file = 0, const QPixmap &icon = 0, AnimationTypeP animation = atpSlideDown ); ~MibitPasswordDialog(); void setSVG(const QString &file); void setIcon(const QPixmap &icon); void setMessage(const QString &msg); void setTextColor(const QString &color); void setAnimationType(const AnimationTypeP &atype) { animType = atype; } void setAnimationRate(const int &r) { animRate = r; } void setMaxHeight(const int &m) { setMaximumHeight(m); maxHeight = m; } void setMaxWidth(const int &m) { setMaximumWidth(m); maxWidth = m; } void setSize(const int &w, const int &h) { setMaxWidth(w); setMaxHeight(h); } void setShakeTTL(const int &timeToLive = 0){ shakeTimeToLive = timeToLive;} //timeToLive = 0 means shake until closed. QString getPassword() { return editPassword->text(); } void cleanPassword() { editPassword->setText(""); } private: QTimeLine *timeLine; QTimeLine *wTimeLine; QTimer *shakeTimer; QLabel *text; QLabel *title; QHBoxLayout *hLayout; QVBoxLayout *vLayout; QLabel *img; //QPushButton *btnClose; QLineEdit *editPassword; AnimationTypeP animType; QWidget *m_parent; int maxWidth; int maxHeight; int animRate; int shakeTimeToLive; bool par; unsigned int parTimes; QString closeMsg; private slots: void animate(const int &step); void shakeIt(); void waveIt(const int &step); //void hideDialog(); void onAnimationFinished(); public slots: void shake(); void wave(); void showDialog( const QString &msg = 0, AnimationTypeP animation = atpSlideDown ); void hideDialog(); protected: void keyPressEvent ( QKeyEvent * event ); signals: void returnPressed(); }; #endif // MIBITPASSWORDDLG_H
4,343
C++
.h
100
40.15
161
0.621781
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,842
mibitfloatpanel.h
hiramvillarreal_iotpos/mibitWidgets/mibitfloatpanel.h
/*************************************************************************** * Copyright (C) 2009 by Miguel Chavez Gamboa * * hiramvillarreal.ap@gmail.com * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #ifndef MIBITFLOATPANEL_H #define MIBITFLOATPANEL_H #include <QSvgWidget> class QTimeLine; class QString; class QHBoxLayout; class QLabel; class QPixmap; /** * This class is used to display an animated floating panel * on Top, Bottom, Left or Right edges of its parent. * Svg themed and borderless. * * The panel content is added with the addWidget() method, * The simple way is to create a QWidget with all its content * with its layout -in designer or by code-. * It will be reparented automatically when added to the panel. * Dont forget to set the panel size according to your needs. * */ enum PanelPosition {Top = 1, Bottom = 2, Left = 3, Right = 4 }; enum PanelModes {pmAuto = 1, pmManual=2}; enum PanelConstants {pMinH= 100, pMinW = 100 }; class MibitFloatPanel : public QSvgWidget { Q_OBJECT public: MibitFloatPanel(QWidget *parent = 0, const QString &file = 0, PanelPosition position = Top, const int &w=100, const int &h=100); ~MibitFloatPanel(); void addWidget(QWidget * widget); void setPosition(const PanelPosition pos); void setSVG(const QString &file); void setMaxHeight(const int &m) { setMaximumHeight(m); maxHeight = m; reposition(); } void setMaxWidth(const int &m) { setMaximumWidth(m); maxWidth = m; reposition(); } void setSize( const int &w, const int &h ) { setMaxHeight(h); setMaxWidth(w); } void setMode(const PanelModes mode) { m_mode = mode; } void reParent(QWidget *newparent); void setHiddenTotally(bool val) { m_hideTotally = val; } private: QTimeLine *timeLine; QHBoxLayout *hLayout; QWidget *m_parent; QString m_fileName; bool canBeHidden; bool m_hideTotally; int maxHeight; int maxWidth; int animRate; PanelPosition m_position; PanelModes m_mode; int margin; signals: void hiddenOnUserRequest(); public slots: void showPanel(); void showPanelDelayed(); void hidePanel() { hideDialog(); } void fixPos(); private slots: void animate(const int &step); void hideOnUserRequest(); void hideDialog(); void onAnimationFinished(); void reposition(); protected: void enterEvent ( QEvent * event ); void leaveEvent ( QEvent * event ); void keyPressEvent ( QKeyEvent * event ); }; #endif // MIBITFLOATPANEL_H
3,791
C++
.h
89
39.292135
132
0.599242
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,843
mibitdialog.h
hiramvillarreal_iotpos/mibitWidgets/mibitdialog.h
/*************************************************************************** * Copyright (C) 2009 by Miguel Chavez Gamboa * * miguel@lemonpos.org * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #ifndef MIBITDIALOG_H #define MIBITDIALOG_H #include <QSvgWidget> class QTimeLine; class QString; class QHBoxLayout; class QVBoxLayout; class QLabel; class QPixmap; class QPushButton; /** * This class is used to display animated dialogs appering on screen's * top or middle. Are svg themed and borderless. * It can also shake it or wave it to take user's attention. * * The animation types are four: * atGrowCenterV: This makes the dialog appear growing from the center in the Y axe. * atGrowCenterH: This makes the dialog appear growing from the center in the X axe. * atSlideDown: This makes the dialog appear sliding down from the top of its parent. * atSlideUp: This makes the dialog appear sliding up from the bottom of its parent. * * */ enum AnimationType { atGrowCenterV=1, atGrowCenterH=2, atSlideDown=3, atSlideUp=4 }; enum Sizes { maxH=300, maxW=400 }; class MibitDialog : public QSvgWidget { Q_OBJECT public: MibitDialog(QWidget *parent = 0, const QString &msg = 0, const QString &file = 0, const QPixmap &icon = 0, AnimationType animation = atSlideDown ); ~MibitDialog(); void showDialog( const QString &msg = 0, AnimationType animation = atSlideDown ); // Tratar de hacer un metodo similar al QDialog::getDouble()... con static void setSVG(const QString &file); void setIcon(const QPixmap &icon); void setMessage(const QString &msg); void setTextColor(const QString &color); void setAnimationType(const AnimationType &atype) { animType = atype; } void setAnimationRate(const int &r) { animRate = r; } void setMaxHeight(const int &m) { setMaximumHeight(m); maxHeight = m; } void setMaxWidth(const int &m) { setMaximumWidth(m); maxWidth = m; } void setSize(const int &w, const int &h) { setMaxWidth(w); setMaxHeight(h); } void setShakeTTL(const int &timeToLive = 0){ shakeTimeToLive = timeToLive;} //timeToLive = 0 means shake until closed. private: QTimeLine *timeLine; QTimeLine *wTimeLine; QTimer *shakeTimer; QLabel *text; QLabel *title; //QLabel *btn; //we will paint the close icon. QHBoxLayout *hLayout; QVBoxLayout *vLayout; QLabel *img; QPushButton *btnClose; AnimationType animType; QWidget *m_parent; int maxWidth; int maxHeight; int animRate; int shakeTimeToLive; bool par; unsigned int parTimes; private slots: void animate(const int &step); void shakeIt(); void waveIt(const int &step); void hideDialog(); void onAnimationFinished(); public slots: void shake(); void wave(); protected: void keyPressEvent ( QKeyEvent * event ); }; #endif // MIBITDIALOG_H
4,170
C++
.h
94
41.117021
151
0.612737
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,844
BasketPriceCalculationService.h
hiramvillarreal_iotpos/src/BasketPriceCalculationService.h
#ifndef IOTPOS_BASKETPRICECALCULATIONSERVICE_H #define IOTPOS_BASKETPRICECALCULATIONSERVICE_H #include <QHash> #include "nouns/BasketPriceSummary.h" #include "nouns/User.h" #include "structs.h" class BasketPriceCalculationService { public: BasketPriceSummary calculateBasketPrice(QHash<qulonglong, ProductInfo> & products, ClientInfo & client, double salesmanDiscount); private: double calculateEntryDiscount(ProductInfo & prod, ClientInfo & client, bool forceGross); BasketEntryPriceSummary calculateBasketEntry(ProductInfo & prod, ClientInfo & client, bool applyDiscounts); }; #endif //IOTPOS_BASKETPRICECALCULATIONSERVICE_H
644
C++
.h
14
43.785714
133
0.8352
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,845
iotposview.h
hiramvillarreal_iotpos/src/iotposview.h
/************************************************************************** * Copyright © 2013-2015 by Hiram R. Villarreal * * hiramvillarreal.ap@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #ifndef IOTPOSVIEW_H #define IOTPOSVIEW_H class QStringList; class QTableWidgetItem; class LoginWindow; class MibitTip; class MibitPasswordDialog; class MibitFloatPanel; class MibitNotifier; #include <qwidget.h> #include <QList> #include <QtSql> #include "enums.h" #include "gaveta.h" #include "loginwindow.h" #include "ui_mainview.h" #include "bundlelist.h" #include "nouns/BasketPriceSummary.h" /** * This is the main view class for iotpos. Most of the non-menu, * non-toolbar, and non-statusbar (e.g., non frame) GUI code should go * here. * * @short Main view * @author Miguel Chavez Gamboa <miguel.chavez.gamboa@gmail.com> * @version 2007.11 * Modified by Daniel A. Cervantes dcchivela@gmail.com */ class iotposView : public QWidget, public Ui::mainview { Q_OBJECT public: iotposView(); void openDB(); virtual ~iotposView(); QString getLoggedUser(); QString getLoggedUserName(QString id); qulonglong getLoggedUserId(QString uname); //BUG FIXED on nov82009: it was unsigned int... int getUserRole(qulonglong id); int getLoggedUserRole() { return loggedUserRole; } QString getCurrentTransactionString(); qulonglong getCurrentTransaction(); QList<int> getTheSplitterSizes(); QList<int> getTheGridSplitterSizes(); int rmSeason; QList<qulonglong> rmExcluded; void setTheSplitterSizes(QList<int> s); void setTheGridSplitterSizes(QList<int> s); bool isTransactionInProgress() { return transactionInProgress;} void cancelByExit(); bool canStartSelling() {return operationStarted;} bool validAdminUser(); void corteDeCaja(); //to allow iotpos class to doit QWidget *frameLeft, *frame; private: QTimer *rmTimer; Ui::mainview ui_mainview; QString loggedUser; QString loggedUserName; int loggedUserRole; qulonglong loggedUserId; qulonglong currentTransaction; qulonglong currentBalanceId; double totalSum; double totalTax; // in money. Gaveta *drawer; bool drawerCreated; bool modelsCreated; bool operationStarted; bool transactionInProgress; bool graphSoldItemsCreated; QSqlDatabase db; LoginWindow *dlgLogin; LoginWindow *dlgPassword; QHash<qulonglong, ProductInfo> productsHash; QSqlTableModel *productsModel; QSqlQueryModel *clientsModel; //for the credits panel, completer. QHash<QString, int> categoriesHash; ClientInfo clientInfo; QHash<QString, ClientInfo> clientsHash; qulonglong buyPoints; double discMoney; double globalDiscount; //% double totalSumWODisc; double subTotalSum; double reservationPayment; QDateTime transDateTime; double lastDiscount; bool completingOrder; QTimer *timerCheckDb, *timerUpdateGraphs; bool availabilityDoesNotMatters; bool doNotAddMoreItems; bool finishingReservation; bool startingReservation; qulonglong reservationId; QHash<qulonglong, SpecialOrderInfo> specialOrders; QSqlRelationalTableModel *historyTicketsModel; MibitTip *tipCode, *tipAmount; MibitPasswordDialog *lockDialog; MibitFloatPanel *currencyPanel; MibitFloatPanel *discountPanel; MibitFloatPanel *creditPanel; MibitNotifier *notifierPanel; double oDiscountMoney; double gTaxPercentage; ClientInfo crClientInfo; CreditInfo crInfo; QDoubleValidator *valPercentage; QDoubleValidator *valMoney; //QMultiHash<qulonglong, BundleInfo> bundlesHash; BundleList *bundlesHash; void loadIcons(); void setUpInputs(); void setupModel(); void setupClientsModel(); RoundingInfo roundUsStandard(const double &number); BasketPriceSummary recalculateBasket(double oDiscountMoney); KPlotObject *objSales; signals: /** * Use this signal to change the content of the statusbar */ void signalChangeStatusbar(const QString& text); /** * Use this signal to change the content of the caption */ void signalChangeCaption(const QString& text); /** * Use this signal to inform that the administrator has logged on. **/ void signalAdminLoggedOn(); void signalSupervisorLoggedOn(); /** * Use this signal to inform that the administrator has logged off. **/ void signalAdminLoggedOff(); void signalSupervisorLoggedOff(); /** * Use this signal to inform that no user has logged on. **/ void signalNoLoggedUser(); /** * Use this signal to inform that an user has logged on (!=admin). **/ void signalLoggedUser(); /** * Use this signal to update the clock on the statusbar */ void signalUpdateClock(); void signalQueryDb(QString code); /** * Signal used to update transaction number */ void signalUpdateTransactionInfo(); /** * Signal used to inform the start of operation. */ void signalStartedOperation(); void signalShowProdGrid(); void signalShowDbConfig(); void signalEnableUI(); void signalDisableUI(); void signalEnableLogin(); void signalDisableLogin(); void signalEnableStartOperationAction(); void signalDisableStartOperationAction(); private slots: void setUpTable(); /** * Slot used to show the "enter code" widget */ void showEnterCodeWidget(); /** * Slot used to show the "search item" widget */ void showSearchItemWidget(); /** * Slot used to search an item description into database, to get the code. */ void doSearchItemDesc(); /** * Slot to search for a product code in the table, if found then qty is incremented. */ bool incrementTableItemQty(QString code, double q); /** * Slot used to get a product info from the database and insert it to the table */ void insertItem(QString code); /** * Slot used to insert an item into the buy list, do the real insert */ int doInsertItem(QString itemCode, QString itemDesc, double itemQty, double itemPrice, double itemDiscount, QString itemUnits); void updateItem(ProductInfo prod); /** * Slot used to delete the current item. */ void deleteSelectedItem(); /** * Slot used to increment qty on doubleclick on an item */ void itemDoubleClicked(QTableWidgetItem* item); /** * Slot used to add clicked item to shopping list... */ void itemSearchDoubleClicked(QTableWidgetItem *item); /** * Slot used to refresh (recalculate) the total due. */ void refreshTotalLabel(); /** * Slot used to display product information on the left panel. */ void displayItemInfo(QTableWidgetItem* item); /** * Slot used to create a new transaction. It gets last transaction number from database, and creates a new one. */ void createNewTransaction(TransactionType type); //NOTE: With parameter transactionType ?? /** * Slot used to finish current TRansaction. It saves transaction on database. */ void finishCurrentTransaction(); /** * Slot used to cancel the current transaction on the database. */ void cancelCurrentTransaction(); void preCancelCurrentTransaction(); void deleteCurrentTransaction(); /** * Slot used to cancel a transaction from database */ void cancelTransaction(qulonglong transactionNumber); void askForIdToCancel(); void askForTicketToReturnProduct(); /** * Slot used to start store operation, gaveta qty is set to 0. */ void startOperation(const QString &adminUser); void _slotDoStartOperation(); void slotDoStartOperation(const bool &ask = true); /** * Slot used to clear the tableWidget, totals, amount and card number. */ void clearUsedWidgets(); /** * Slot used to print the ticket, show a frame message and wait a few seconds... **/ void printTicket(TicketInfo ticket); /** * Slot used to print balance for the user. */ void printBalance(QStringList lines); void showBalance(QStringList lines); /** * This slot is used to make a balance for the user (initial + in - out = drawer amount). */ //void corteDeCaja(); GONE TO PUBLIC void doCorteDeCaja(); void endOfDay(); void startAgain(); /** * Slot used to get the row where an item with code is at the main table. * Returns -1 if not found, else returns table row where is located. **/ int getItemRow(QString c); void buttonDone(); void checksChanged(); void focusPayInput(); void plusPressed(); void setupGridView(); void setupGraphs(); void updateGraphs(); void doEmitSignalQueryDb(); void settingsChanged(); void settingsChangedOnInitConfig(); void login(); void setupDB(); void connectToDb(); void setupClients(); void timerTimeout(); void clearLabelSearchMsg(); void goSelectCardAuthNumber(); void listViewOnMouseMove(const QModelIndex & index); void listViewOnClick( const QModelIndex & index ); void clientChanged(); void updateClientInfo(); void updateModelView(); void showProductsGrid(bool show); void showPriceChecker(); void hideProductsGrid(); void populateCategoriesHash(); void populateCardTypes(); void setFilter(); void showChangeDate(); void showReprintTicket(); void setupTicketView(); void setupHistoryTicketsModel(); void printTicketFromTransaction(qulonglong transactionNumber); void printSelTicket(); void setHistoryFilter(); void btnTicketsDone() { ui_mainview.mainPanel->setCurrentIndex(0); }; void itemHIDoubleClicked(const QModelIndex &index); void cashOut(); void cashIn(); void cashAvailable(); void freezeWidgets(); void unfreezeWidgets(); void addSpecialOrder(); void specialOrderComplete(); void lockScreen(); void unlockScreen(); void suspendSale(); void resumeSale(); void changeSOStatus(); void updateTransaction(); void updateBalance(bool finish); //implies the drawer content void insertBalance(); void occasionalDiscount(); void applyOccasionalDiscount(); void changeDiscValidator(); double getTotalQtyOnList(const ProductInfo &info); void log(const qulonglong &uid, const QDate &date, const QTime &time, const QString &text); void syncSettingsOnDb(); void getCurrencies(); void comboCurrencyOnChange(); void doCurrencyConversion(); void acceptCurrencyConversion(); void reserveItems(); void suspendReservation(); void resumeReservation(); void postponeReservation(); void addReservationPayment(); //used to add a payment to a reservation without paying it totally. void insertCashInForReservationPayment(const qulonglong &rid, const double &amount); void showCredits(); void filterClientForCredit(); void filterClient(); void calculateTotalForClient(); void showCreditPayment(); void tenderedChanged(); void doCreditPayment(); void insertCashInForCredit(const CreditInfo &credit, const double &amount); void printCreditReport(); void qtyChanged(QTableWidgetItem *item); void modifyClientsFilterModel(); void modifyClientsFilterModelB(); void verifyDiscountEntry(); void createClient(); void resizeSearchTable(); void resizeSearchTableSmall(); void on_rbFilterByPopularity_clicked(); void on_rbFilterByCategory_clicked(); }; #endif // IOTPOSVIEW_H
12,993
C++
.h
371
30.3531
131
0.684144
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,846
structs.h
hiramvillarreal_iotpos/src/structs.h
/************************************************************************** * Copyright © 2007-2011 by Miguel Chavez Gamboa * * miguel@lemonpos.org * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * **************************************************************************/ #ifndef MYSTRUCTS_H #define MYSTRUCTS_H #include <QString> #include <QByteArray> #include <QPixmap> #include <QDateTime> #include <QDate> #include <QHash> struct ProductInfo { qulonglong code; QString desc; double price; double disc; double discpercentage; bool validDiscount; double cost; double tax; double extratax; double totaltax;//in money... QByteArray photo; double stockqty; int units; QString unitStr; int department; int category; int subcategory; double utility; int row; // New: Sept 30, 2007: To store the row where the product is located in the listView. qulonglong points; //New: Dec 15 2007: To store the points the product gives. double qtyOnList; double purchaseQty; //New: Jan 13 2007: For purchase editor... qulonglong lastProviderId; QString alphaCode; QString vendorCode; // ben branch double soldUnits; // mch 21Nov09 FOR PRINTED REPORT - LOW STOCK // for grouped products and special orders bool isAGroup; bool isARawProduct; QString groupElementsStr; double groupPriceDrop; //for later use: qulonglong taxmodelid; QString taxElements; //aug 11 2011, for 0.9.4.rc9 bool hasUnlimitedStock; bool isNotDiscountable; }; struct UserInfo { unsigned int id; QString username; QString password; QString salt; QString name; QString address; QString cell; QString phone; QByteArray photo; int role; }; struct ClientInfo { unsigned int id; QString code; QString name; QString address; QString phone; QString cell; qulonglong points; double discount; QByteArray photo; QDate since; }; struct OfferInfo { qulonglong productCode; double discount; QDate dateStart; QDate dateEnd; }; struct TransactionInfo { qulonglong id; int type; double amount; QDate date; QTime time; double paywith; double changegiven; int paymethod; int state; qulonglong userid; qulonglong clientid; QString cardnumber; QString cardauthnum; QString cardTypeStr; int cardType; int itemcount; QString itemlist; double disc; double discmoney; qulonglong points; double utility; int terminalnum; //QString groups; //DEPRECATED QString specialOrders; qulonglong providerid; qulonglong balanceId; //to store balance where it was sold. For SESSIONS. double totalTax; //in money. }; struct BalanceInfo { qulonglong id; QDateTime dateTimeStart; QDateTime dateTimeEnd; qulonglong userid; QString username; double initamount; double in; double out; double cash; double card; QString transactions; int terminal; QString cashflows;//28DIC09 bool done; }; struct PrintBalanceInfo { QString thBalanceId; QString storeName; QString storeAddr; QString thTitle; QString thDeposit; QString thIn; QString thOut; QString thInDrawer; QString thTitleDetails; QString thTitleCFDetails; QString thTrId; QString thTrTime; QString thTrAmount; QString thTrPaidW; QString thTrPayMethod; QPixmap storeLogo; QString startDate; QString endDate; // qtys as string - local aware / translated QString initAmount; QString inAmount; QString outAmount; QString cashAvailable; bool logoOnTop; QString thCFType; QString thCFReason; QString thCFDate; QStringList trList; QStringList cfList; QString reservationNote; QString notCashNote; }; struct pieProdInfo { double count; QString name; QString unitStr; qulonglong code; }; struct ProfitRange { double min; double max; }; struct TicketLineInfo { double qty; QString unitStr; QString desc; double price; double disc; double partialDisc; double total; double gtotal; QString geForPrint; bool completePayment; bool isGroup; double payment; QDateTime deliveryDateTime; double tax; //total tax in Percentage. }; struct TicketInfo { qulonglong number; double total; //this is the total amount of THIS TICKET. double change; double paidwith; int itemcount; QString cardnum; QString cardAuthNum; bool paidWithCard; double clientDisc; double clientDiscMoney; qulonglong buyPoints; qulonglong clientPoints; qulonglong clientid; // 14 Abril 08 QList<TicketLineInfo> lines; QDateTime datetime; bool hasSpecialOrders; bool completingSpecialOrder; double totalTax; QDateTime deliveryDT; double soTotal; //this is the total for the SO (nextpayment + prepayment) QString subTotal; QString terminal; //for reservations: bool isAReservation; bool reservationStarted; double reservationPayment; double purchaseTotal; qulonglong reservationId; }; struct PrintTicketInfo { QString storeName; QString storeAddr; QString storePhone; QString ticketMsg; QPixmap storeLogo; QString salesPerson; QString terminal; QString thPhone; QString thDate; QString thProduct; QString thQty; QString thPrice; QString thTotal; QString thTotals; QString thDiscount; QString thArticles; QString thPoints; QString thTicket; QString thPaid; QString thChange; QString tDisc; QString thCard; QString thCardAuth; double totDisc; TicketInfo ticketInfo; bool logoOnTop; QString paymentStrComplete; QString paymentStrPrePayment; QString nextPaymentStr; QString lastPaymentStr; QString deliveryDateStr; QString clientDiscountStr; double clientDiscMoney; QString randomMsg; QString thChangeStr; QString taxes; QString thTax; QString thTendered; QString thSubtotal; QString subtotal; QString resTotalAmountStr; QString hdrReservation; }; //TODO: add grouped products and special orders // is it convenient? in case a pack of 6 water botles is not convenient, but a combo "My burger package" // consisting of one burger, one soda and one fried potatoes. struct TransactionItemInfo { qulonglong transactionid; int position; qulonglong productCode; double qty; double points; QString unitStr; double cost; double price; double disc; double total; QString name; //for special orders, also productCode will be 0 for special orders QString soId; double payment; bool completePayment; bool isGroup; QDateTime deliveryDateTime; double tax; // total tax in percentage. }; struct CashFlowInfo { qulonglong id; int type; qulonglong userid; double amount; QString reason; QDate date; QTime time; qulonglong terminalNum; //next are for cashflow into balance printing QString typeStr; }; struct AmountAndProfitInfo { double amount; double profit; }; struct PrintEndOfDayInfo { QString storeName; QString storeAddr; QPixmap storeLogo; QString salesPerson; QString terminal; QString thTitle; QString thDate; QString thTime; QString thTicket; QString thAmount; QString thProfit; QString thPayMethod; QString thTotalSales; QString thTotalProfit; QString thTotalTaxes; QStringList trLines; bool logoOnTop; }; struct PrintLowStockInfo { QString storeName; QString storeAddr; QPixmap storeLogo; QString hTitle; QString hDate; //and time QString hDesc; QString hCode; QString hQty; QString hUnitStr; QString hSoldU; QStringList pLines; bool logoOnTop; }; struct SpecialOrderInfo { qulonglong orderid; qulonglong saleid; QString name; double qty; double price; double cost; int status; int units; QString unitStr; QString groupElements; QString notes; int insertedAtRow; QString geForPrint; double payment; //anticipos bool completePayment; QDateTime dateTime; qulonglong completedOnTrNum; QDateTime deliveryDateTime; qulonglong userId; qulonglong clientId; double averageTax; double disc; }; struct GroupInfo { QString name; double cost; double price; double taxMoney; double tax; double priceDrop; double count; // total of items in the group bool isAvailable; //based on stockqty for each product (and its qtys). QHash<qulonglong, ProductInfo> productsList; }; struct CurrencyInfo { qulonglong id; QString name; double factor; }; struct ReservationInfo { qulonglong id; qulonglong transaction_id; qulonglong client_id; QDate date; double payment; double total; double totalTaxes; double profit; int status; double discount; QString item_discounts; }; struct ReservationPayment { qulonglong id; qulonglong reservation_id; double amount; QDate date; }; struct CreditInfo { qulonglong id; qulonglong clientId; double total; }; struct CreditHistoryInfo { qulonglong id; qulonglong customerId; qulonglong saleId; QDate date; QTime time; double amount; }; struct RoundingInfo { QString strResult; double doubleResult; int intDecPart; int intIntPart; }; struct FoliosPool { QDate fechaAprobacion; //FIXME: Es Fecha o Fecha Y HORA ??? QString numAprobacion; //El número de aprobación del folio asignado por SICOFI. Este es el primary key. QByteArray cbb; QString folioInicial; // 'A101', incluye la serie (A,B,C...) QString folioFinal; // 'A200' int cantidadFolios; }; //NOTE:Tomar en cuenta 'race conditions'. Si dos terminales piden un folio al mismo tiempo, podrian tener el mismo numero ambos, siendo que esta 'usado=false' // Para solucionar esto, en el mismo momento de pedir un folio, se marca como usado. (como en un stack, se retira.) // Un problema es que no se puede regresar al stack con 'usado=false', porque entonces se podrian estar usando folios no consecutivos. // ejemplo: Hoy dos terminales compiten por un folio, una obtiene el A101, otra el A102. La del A101 cancela y se regresa A101 con usado=false. // Al dia siguiente, se pide un folio libre, y A102 se devuelve. Entonces A101 se factura con una fecha POSTERIOR a la de A102. Este // seria un problema ante hacienda porque A101 es de una fecha posterior a A102 y no deberia de ser. struct FolioInfo { QString poolId; //al pool que pertenece (La serie de folios pedidos al sat) QString numero; // Este es la primary key de la tabla, asi no se permiten duplicados. bool usado; //indica si el folio ya fue usado o esta libre para ser usado. bool valido; //indica si el folio es valido o cancelado. QByteArray cbb; }; struct FacturaCBB { QDate fecha; QString folio; //este es el primary key QString authFolios; QDate fechaAutFolios; QByteArray cbb; //QR Code, PNG. NOTE: Podia ser un apuntador a otra tabla, ya que una serie de folios comparten CBB. bool valida; //Para cancelar facturas. QString nombreCliente; QString RFCCliente; QString direccionCliente; QList<TicketLineInfo> lineas; qulonglong trId; double subTotal; // Sin Impuestos, sin descuentos. double descuentos; double impuestos; // IVA... alguno mas ? double impuestosTasa; // impuestos en % double total; // Incluyendo iva, y descuentos. ///not stored on db: QString totalLetra; QString storeName; QString storeRFC; QString storeRegimen; QString storeAddr; QString storeLugar; QString storePhone; QPixmap storeLogo; }; //TODO: Operaciones relacionadas con facturas: // Cancelacion // Notas de Credito (No necesario sobre una factura) [Ver si esto requiere FOLIO del SAT] // Pagos a una factura, saldo sobre la factura. Relacion entre factura->Credito->Abono struct BundleInfo { qulonglong product_id; double price; double qty; }; #endif
13,727
C++
.h
507
24.207101
158
0.680194
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,847
specialordereditor.h
hiramvillarreal_iotpos/src/specialordereditor.h
/*************************************************************************** * Copyright (C) 2009-2010 by Miguel Chavez Gamboa * * hiramvillarreal.ap@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #ifndef SPECIALORDEREDITOR_H #define SPECIALORDEREDITOR_H #include <KDialog> #include <QDate> #include <QtGui> #include <QPixmap> #include <QtSql> #include "ui_special_order.h" #include "../src/structs.h" class MibitTip; class MibitFloatPanel; class QDateTime; class SpecialOrderUI : public QFrame, public Ui::specialOrderEditor { Q_OBJECT public: SpecialOrderUI( QWidget *parent=0); }; class SpecialOrderEditor : public KDialog { Q_OBJECT public: SpecialOrderEditor( QWidget *parent=0, bool newOne=true ); ~SpecialOrderEditor(); //qulonglong getOrderId() { return ui->lbl->text().toULongLong(); }; QString getDescription(); double getCost() { return groupInfo.cost; } double getPrice() { return priceEach; } double getQty() { return ui->editQty->text().toDouble(); } QString getNotes() { return ui->editNotes->toPlainText(); } qulonglong getTransId() { return m_transId; } double getPayment() { return ui->editPayment->value()/ui->editQty->value();} ///we divide the total payment by the qty of items ordered, to report them to iotposview... iotposview expects the payment to be the price for the item to be inserted (so) in order to calculate the total sale. GroupInfo getGroupHash(); QString getGroupElementsStr(); int getStatus(); QString getContentNames(); QDateTime getDateTime() { return dateTime; } QDateTime getDeliveryDateTime() { return ui->deliveryDT->dateTime(); } qulonglong getUserId(); qulonglong getClientId(); void setDb(QSqlDatabase database); void setCost(double c) { groupInfo.cost = c; } //NOTE:undesireable void setPrice(double p) { priceEach = p; } void setQty(double q) {ui->editQty->setValue(q); } void setGroupElements(QString e); void setModel(QSqlTableModel *model); void setTransId(qulonglong id) {m_transId = id; ui->lblTransId->setText(QString::number(id)); } void setPayment(double d) { ui->editPayment->setValue(d); } void setDateTime(QDateTime dt) { dateTime = dt; } void setDeliveryDateTime(QDateTime dt) { ui->deliveryDT->setDateTime(dt); dateTime = dt; } void setDeliveryDateTimeEnabled(bool value) { ui->deliveryDT->setEnabled(value); } void setUsername(QString name); void setClientsComboEnabled(bool val) { ui->clientsCombo->setEnabled(val); } void setClientName(QString name); private slots: void calculateCost(); void checkFieldsState(); void applyFilter(const QString &text); void addItem(); void removeItem(); void itemDoubleClicked(QTableWidgetItem* item); void populateUsersCombo(); void populateClientsCombo(); void checkDate(QDateTime dt); void checkValidInfo(); void hideError(); void createClient(); void enableCreateClient(); void updateNoteLength(); protected slots: virtual void slotButtonClicked(int button); private: SpecialOrderUI *ui; QSqlDatabase db; GroupInfo groupInfo; bool m_modelAssigned; QSqlTableModel *m_model; qulonglong m_transId; double priceEach; double paymentEach; QDateTime dateTime; MibitTip *qtyTip; MibitTip *groupTip; MibitFloatPanel * newClientPanel; }; #endif
4,843
C++
.h
105
42.32381
294
0.607506
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,848
soselector.h
hiramvillarreal_iotpos/src/soselector.h
/*************************************************************************** * Copyright (C) 2009-2010 by Miguel Chavez Gamboa * * hiramvillarreal.ap@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #ifndef SOSELECTOR_H #define SOSELECTOR_H #include <KDialog> #include <QDate> #include <QtGui> #include <QPixmap> #include <QtSql> #include "ui_soselector.h" #include "../src/structs.h" class MibitTip; class QDateTime; class SOSelectorUI : public QFrame, public Ui::soSelector { Q_OBJECT public: SOSelectorUI( QWidget *parent=0); }; class SOSelector : public KDialog { Q_OBJECT public: SOSelector( QWidget *parent=0 ); ~SOSelector(); void setDb(QSqlDatabase database); qulonglong getSelectedTicket() { return ticketNumber; } private slots: void applyFilter(); void itemClicked(const QModelIndex &index); void setupModel(); void selectItem(); protected slots: virtual void slotButtonClicked(int button); private: SOSelectorUI *ui; QSqlDatabase db; bool m_modelAssigned; QSqlRelationalTableModel *soModel; //SpecialOrderInfo selectedSO; qulonglong ticketNumber; }; #endif
2,447
C++
.h
60
38.033333
77
0.539529
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,849
ticketpopup.h
hiramvillarreal_iotpos/src/ticketpopup.h
/*************************************************************************** * Copyright (C) 2009 by Miguel Chavez Gamboa * * hiramvillarreal.ap@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #ifndef TICKETPOPUP_H #define TICKETPOPUP_H #include <QtGui> #include <QString> #include <QPainter> class QGridLayout; class QTextEdit; class QTimer; class QKeyEvent; class TicketPopup : public QDialog { Q_OBJECT private: QGridLayout *gridLayout; QLabel *imagelabel; QTextEdit *editText; QTimer *timer; protected: void paintEvent(QPaintEvent *e); public: TicketPopup(QString text="", QPixmap pixmap=0, int timeToClose=1000); void setPixmap(QPixmap pixmap) { imagelabel->setPixmap(pixmap); } void popup(); virtual void paint(QPainter *) {} virtual void keyPressEvent( QKeyEvent * event); signals: void onTicketPopupClose(); private slots: void closeIt(); }; #endif
2,167
C++
.h
50
40.96
76
0.52891
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,850
misc.h
hiramvillarreal_iotpos/src/misc.h
/*************************************************************************** * Copyright (C) 2013-2015 by Hiram R. Villarreal * * hiramvillarreal.ap@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #ifndef MISC_H #define MISC_H class QByteArray; class QPixmap; class QFontMetrics; class QStringList; class QString; /** * This class is for Misc code. * Actual Stuff: pixmap2ByteArray in diferent versions. * * @author Miguel Chavez Gamboa <miguel.chavez.gamboa@gmail.com> * @version 0.1 */ class Misc { public: static QByteArray pixmap2ByteArray(QPixmap *pix, bool scale=true); static QByteArray pixmap2ByteArray(QPixmap *pix, int maxW, int maxH); static QStringList stringToParagraph(const QString &str, const QFontMetrics &fm, const double &maxL); static QStringList stringToParagraph(const QString &str, const int &maxChars); }; #endif
2,138
C++
.h
41
49.902439
105
0.528257
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,851
dialogclientdata.h
hiramvillarreal_iotpos/src/dialogclientdata.h
/*************************************************************************** * Copyright (C) 2012 by Miguel Chavez Gamboa * * hiramvillarreal.ap@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #ifndef DIALOGCLIENTDATA_H #define DIALOGCLIENTDATA_H #include <KDialog> #include <QtGui> #include "ui_datoscliente.h" class DialogClientDataUI : public QFrame, public Ui::datosCliente { Q_OBJECT public: DialogClientDataUI( QWidget *parent=0 ); }; class DialogClientData : public KDialog { Q_OBJECT public: DialogClientData( QWidget *parent=0 ); ~DialogClientData(); QString getNombre(){ return ui->editNombre->text();}; QString getRFC(){ return ui->editRFC->text();}; QString getDireccion(); private slots: void validate(); private: DialogClientDataUI *ui; }; #endif
2,087
C++
.h
45
43.755556
77
0.509109
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,853
loginwindow.h
hiramvillarreal_iotpos/src/loginwindow.h
/*************************************************************************** * Copyright (C) 2013-2015 by Hiram R. Villarreal * * hiramvillarreal.ap@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #ifndef _LOGINWINDOW_H_ #define _LOGINWINDOW_H_ #include <QDialog> #include <QHash> #include <QtSql> #include "structs.h" class QLineEdit; class QLabel; class QPushButton; class QString; class QHBoxLayout; class QVBoxLayout; class QGridLayout; class QSpacerItem; class QSqlDatabase; /** This class is for asking login and password. * Derived from QDialog, but to use full screen and no borders. * Also to have an image in the background. * * @short A Login Window * @author Miguel Chavez Gamboa miguel.chavez.gamboa@gmail.com **/ class LoginWindow : public QDialog { Q_OBJECT private: QLineEdit *editUsername; QLineEdit *editPassword; QLabel *labelPrompt; QLabel *imageError; QLabel *mainImage; QLabel *labelError; QLabel *labelUsername; QLabel *labelPassword; QLabel *labelCaption; QPushButton *btnOk; QPushButton *btnQuit; QVBoxLayout *vLayout; QVBoxLayout *editsLayout; QHBoxLayout *errorLayout; QHBoxLayout *middleLayout; QHBoxLayout *okLayout; QHBoxLayout *quitLayout; QGridLayout *gridLayout; QSpacerItem *spacerItemBottom; QSpacerItem *spacerItemTop; QHash<QString, UserInfo> uHash; QSqlDatabase db; bool wantQuit; qulonglong userId; public: enum Mode { FullScreen = 0, PasswordOnly = 1 }; LoginWindow::Mode currentMode; LoginWindow(QString caption, QString prompt, LoginWindow::Mode mode=LoginWindow::FullScreen); ~LoginWindow(); QString username(); QString password(); int getUserRole() { return userRole; } qulonglong getUserId(); void clearLines(); bool checkPassword(); void setPrompt(QString text); void setCaption(QString text); void showErrorMessage(QString text); void setDb(QSqlDatabase database); bool wantToQuit(); void setUsername(QString un); void setUsernameReadOnly(bool val); void focusPassword(); void reloadUsers(); private: int userRole; protected slots: void acceptIt(); void setQuit(); void hideError(); void showAdminPhoto(); void updateUserPhoto(const QString &); QHash<QString, UserInfo> getUsers(); private slots: virtual void paintEvent(QPaintEvent*); }; #endif
3,790
C++
.h
108
31.194444
77
0.593511
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,854
hash.h
hiramvillarreal_iotpos/src/hash.h
/*************************************************************************** * Copyright (C) 2013-2015 by Hiram R. Villarreal * * hiramvillarreal.ap@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #ifndef HASH_H #define HASH_H class QString; class QByteArray; /** * This class is for hashing a password using SHA1 and returning as a QString. * Based on KWallet code. * * @author Miguel Chavez Gamboa <miguel.chavez.gamboa@gmail.com> * @version 0.1 */ class Hash { public: static QByteArray getCheapSalt(); static QByteArray getSalt(); static QString password2hash(const QByteArray& password); }; #endif
1,931
C++
.h
38
47.894737
80
0.482521
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,855
sostatus.h
hiramvillarreal_iotpos/src/sostatus.h
/*************************************************************************** * Copyright (C) 2009-2010 by Miguel Chavez Gamboa * * hiramvillarreal.ap@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #ifndef SOSTATUS_H #define SOSTATUS_H #include <KDialog> #include <QDate> #include <QtGui> #include <QPixmap> #include <QtSql> #include "ui_sostatus.h" #include "../src/structs.h" class MibitTip; class QDateTime; class SOStatusUI : public QFrame, public Ui::soStatus { Q_OBJECT public: SOStatusUI( QWidget *parent=0); }; class SOStatus : public KDialog { Q_OBJECT public: SOStatus( QWidget *parent=0 ); ~SOStatus(); void setDb(QSqlDatabase database); qulonglong getSelectedTicket() { return ticketNumber; } int getStatusId(); private slots: void applyFilter(); void itemClicked(const QModelIndex &index); void setupModel(); void selectItem(); void populateStatusCombo(); protected slots: virtual void slotButtonClicked(int button); private: SOStatusUI *ui; QSqlDatabase db; bool m_modelAssigned; QSqlRelationalTableModel *soModel; qulonglong ticketNumber; }; #endif
2,451
C++
.h
61
37.409836
77
0.534845
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,856
resume.h
hiramvillarreal_iotpos/src/resume.h
/*************************************************************************** * Copyright (C) 2009-2010 by Miguel Chavez Gamboa * * hiramvillarreal.ap@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #ifndef RESUME_H #define RESUME_H #include <KDialog> #include <QDate> #include <QtGui> #include <QPixmap> #include <QtSql> #include "ui_resume.h" #include "../src/structs.h" class MibitTip; class QDateTime; class QTime; class QDate; class ResumeDialogUI : public QFrame, public Ui::resumeDialog { Q_OBJECT public: ResumeDialogUI( QWidget *parent=0); }; class ResumeDialog : public KDialog { Q_OBJECT public: ResumeDialog( QWidget *parent=0 ); ~ResumeDialog(); void setDb(QSqlDatabase database); void setUserId(qulonglong id) { userId = id; } qulonglong getSelectedTransaction() { return trNumber; } qulonglong getSelectedClient() { return clientId; } QDate getTrDate() { return trDate; } QTime getTrTime() { return trTime; } QList<ProductInfo> getProductsList() { return pList; } QList<SpecialOrderInfo> getSOList() { return soList; } private slots: void itemClicked(const QModelIndex &index); void item_Clicked(const QModelIndex &index, const QModelIndex &indexp); void setupModel(); void selectItem(); void filterClient(); protected slots: virtual void slotButtonClicked(int button); private: ResumeDialogUI *ui; QSqlDatabase db; bool m_modelAssigned; QSqlRelationalTableModel *trModel; qulonglong trNumber; qulonglong userId; qulonglong clientId; QDate trDate; QTime trTime; QList<ProductInfo> pList; QList<SpecialOrderInfo> soList; }; #endif
3,031
C++
.h
74
37.905405
78
0.559173
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,858
enums.h
hiramvillarreal_iotpos/src/enums.h
/************************************************************************** * Copyright © 2007-2011 by Miguel Chavez Gamboa * * miguel@lemonpos.org * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #ifndef MYENUMS_H #define MYENUMS_H enum TransactionType {tSell=1, tBuy=2, tChange=3, tReturn=4, tPayment=5, tOutOther=6}; enum PaymentType {pUnknown=99, pCash=1, pCard=2, pOwnCredit=3 }; enum cashFlowType {ctCashOut=1, ctCashOutMoneyReturnOnCancel=2, ctCashOutMoneyReturnOnProductReturn=3, ctCashIn=4, ctCashInReservation=5, ctCashOutReservation=6, ctCashInCreditPayment=7, ctCashInDebit=8}; enum TransactionState {tNotCompleted=1, tCompleted=2, tCancelled=3, tPOPending=4, tPOCompleted=5, tPOIncomplete=6, tReserved=7, tCompletedOwnCreditPending=8 /*8->Really not pending*/ , tCompletedOwnCreditPaid=9 /*9->Not used*/ }; enum SellUnits {uPiece=1, uWeightKg=2, uLengthMts=3, uVolumeLitre=4, uVolumeCubicMts=5}; //not needed anymore stored on database enum {colCode=0, colQty=1, colUnits=2, colDesc=3, colPrice=4, colDisc=5, colDue=6 }; //column names and numbers.. enum {pageMain=0, pageSearch=1, pageReprintTicket=2, pageRerturnProducts=3, pageAdds=4}; enum userRoles {roleBasic=1, roleAdmin=2, roleSupervisor=3 }; enum soStatus {stPending=0, stInProgress=1, stReady=2, stDelivered=3, stCancelled=4}; enum reservationState {rPending=1, rCompleted=2, rCancelled=3}; static const char db_version[] = "0950"; static const char db_hash[] = ""; //here the idea is to hash the db file to compare the installed one with released versions. #endif
2,880
C++
.h
34
82.941176
229
0.578576
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,859
pricechecker.h
hiramvillarreal_iotpos/src/pricechecker.h
/*************************************************************************** * Copyright (C) 2013-2015 by Hiram R. Villarreal * * hiramvillarreal.ap@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #ifndef PRICECHECKER_H #define PRICECHECKER_H #include <KDialog> #include <QtGui> #include "ui_checker.h" class QSqlDatabase; class Azahar; class PriceCheckerUI : public QFrame, public Ui::priceChecker { Q_OBJECT public: PriceCheckerUI( QWidget *parent=0 ); }; class PriceChecker : public KDialog { Q_OBJECT public: PriceChecker( QWidget *parent=0 ); ~PriceChecker(); public slots: void checkIt(); void setDb(QSqlDatabase database); private: PriceCheckerUI *ui; QPixmap pix; Azahar *myDb; private slots: virtual void paintEvent(QPaintEvent*); }; #endif
2,078
C++
.h
49
39.795918
77
0.509911
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,860
reservations.h
hiramvillarreal_iotpos/src/reservations.h
/*************************************************************************** * Copyright (C) 2010 by Miguel Chavez Gamboa * * hiramvillarreal.ap@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #ifndef RESERVATIONS_H #define RESERVATIONS_H #include <KDialog> #include <QDate> #include <QtGui> #include <QPixmap> #include <QtSql> #include "ui_reservations.h" #include "../src/structs.h" #include "../src/enums.h" #include "gaveta.h" class QDateTime; class QTime; class QDate; class MibitFloatPanel; class ReservationsDialogUI : public QFrame, public Ui::reservationsDialog { Q_OBJECT public: ReservationsDialogUI( QWidget *parent=0); }; class ReservationsDialog : public KDialog { Q_OBJECT public: ReservationsDialog( QWidget *parent=0 , Gaveta *theDrawer=0, int userid=0); ~ReservationsDialog(); void setDb(QSqlDatabase database); qulonglong getSelectedTransaction() { return trNumber; } qulonglong getSelectedReservation() { return rNumber; } qulonglong getSelectedClient() { return clientId; } QDate getTrDate() { return trDate; } double getReservationPayment() { return rPayment; } double getReservationProfit() { return rProfit; } QList<ProductInfo> getProductsList() { return pList; } QString getItemDiscounts() { return item_discounts; } private slots: void itemClicked(const QModelIndex &index); void item_Clicked(const QModelIndex &index, const QModelIndex &indexp); void setupModel(); void selectItem(); void cancelReservation(); protected slots: virtual void slotButtonClicked(int button); private: ReservationsDialogUI *ui; QSqlDatabase db; bool m_modelAssigned; QSqlRelationalTableModel *trModel; qulonglong trNumber; qulonglong rNumber; qulonglong clientId; double rPayment; QDate trDate; QTime trTime; QList<ProductInfo> pList; MibitFloatPanel *panel; Gaveta *drawer; int userId; QString item_discounts; double rProfit; }; #endif
3,364
C++
.h
82
37.878049
79
0.580635
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,861
productdelegate.h
hiramvillarreal_iotpos/src/productdelegate.h
/*************************************************************************** * Copyright (C) 2013-2015 by Hiram R. Villarreal * * hiramvillarreal.ap@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #ifndef PRODUCTDELEGATE #define PRODUCTDELEGATE class QMouseEvent; class QPainEvent; #include <QItemDelegate> class ProductDelegate : public QItemDelegate { Q_OBJECT public: ProductDelegate(QWidget *parent = 0) : QItemDelegate(parent) {} QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const; protected: void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const; }; #endif
1,933
C++
.h
34
54.529412
102
0.508995
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,862
bundlelist.h
hiramvillarreal_iotpos/src/bundlelist.h
/*************************************************************************** * Copyright © 2012 by Miguel Chavez Gamboa * * hiramvillarreal.ap@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #ifndef BUNDLELIST_H #define BUNDLELIST_H #include <QMultiHash> #include <QtSql> #include "structs.h" /** * This class is for store bundles at runtime. * * @short BundleList Class * @author Miguel Chavez Gamboa <miguel@iotpospos.org> * @version 0.1 */ class BundleList : public QObject { Q_OBJECT public: BundleList(); void addItem(const BundleInfo &bundle, const int &maxItems); //adds an item to a bundle slot or creates a new bundle if needed. maxItems is the maximum slots for the item type. bool contains(const qulonglong &itemCode); void clear() { bundles.clear(); }; void debugAll(); void setDb(QSqlDatabase database); private: QMultiHash<qulonglong,BundleInfo> bundles; QSqlDatabase db; void insertNewBundle(const BundleInfo &bndl, const int max); //private slots: //TODO: Create signals for emiting when completing a task. To redraw the item in the tableWidget. //TODO: Create slots for doing a task when the UI code has to do something: EXAMPLE: Remove/Decrement a product in the tableWidget/productsHash. }; #endif
2,567
C++
.h
50
48.54
180
0.555022
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,863
gaveta.h
hiramvillarreal_iotpos/src/gaveta.h
/*************************************************************************** * Copyright (C) 2013-2015 by Hiram R. Villarreal * * hiramvillarreal.ap@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #ifndef _Gaveta_H_ #define _Gaveta_H_ #include <QList> class QDateTime; /** * This class is for store money control. * * @short Gaveta Class * @author Miguel Chavez Gamboa <miguel.chavez.gamboa@gmail.com> * @version 0.1 */ class Gaveta { public: Gaveta(); ~Gaveta(); /** Used only at the beggining. each time is empty or filled. **/ void setPrinterDevice(QString file); void setAvailableInCash(double amount); void setAvailableInCard(double amount); void setStartDateTime(QDateTime datetime); void setInitialAmount(double qty); /** Used each time a transaction is completed: Out **/ void substractCash(double amount); void substractCard(double amount); /** Used each time a transaction is completed : In **/ void addCash(double amount); void addCard(double amount); //MCH 22sept07 void incCardTransactions(); void incCashTransactions(); double getAvailableInCash(); double getAvailableInCard(); double getInitialAmount(); double getInAmount(); double getOutAmount(); QDateTime getStartDateTime(); QList<qulonglong> getTransactionIds(); int getTransactionsCount(); int getCashTransactionsCount(); int getCardTransactionsCount(); void insertTransactionId(qulonglong id); bool isUnused(); void open(); QList<qulonglong> getCashflowIds(); void insertCashflow(qulonglong id); void reset(); private: void addLog(double qty); void clearLog(); double availableInCash; double availableInCard; double in; //Not considered the initialAmount deposited by admin. double out; double initialAmount; int cashTransactions; int cardTransactions; int totalTransactions; bool unused; QList<qulonglong> tIds; QList<double> log; QList<qulonglong> cashflowIds; QDateTime startDateTime; QString printerDevice; }; #endif
3,506
C++
.h
84
38.369048
77
0.567155
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,864
iotpos.h
hiramvillarreal_iotpos/src/iotpos.h
/*************************************************************************** * Copyright (C) 2013-2015 by Hiram R. Villarreal * * hiramvillarreal.ap@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #ifndef IOTPOS_H #define IOTPOS_H #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <kxmlguiwindow.h> #include "ui_prefs_base.h" #include "ui_store_data.h" #include "ui_prefs_db.h" #include "ui_pref_style.h" #include "ui_pref_security.h" #include "ui_pref_printers.h" class iotposView; /** * This class serves as the main window for iotpos. It handles the * menus, toolbars, and status bars. * * @short Main window class * @author Miguel Chavez Gamboa <miguel.chavez.gamboa@gmail.com> * @version 2007.11 */ class iotpos : public KXmlGuiWindow { Q_OBJECT public: /** * Default Constructor */ iotpos(); /** * Default Destructor */ virtual ~iotpos(); public Q_SLOTS: // DBus interface protected: /** * Method to load the users file into the configuration widget's list */ void populateUsersList(); /** * Method used to populate available styles in the configuration list... */ void populateStyleList(); private slots: /** * Slot used to launching the preferences dialog. */ void optionsPreferences(); /** * Slot used to changing the mainwindow's status bar */ void changeStatusbar(const QString& text); /** * Slot used to changing the mainwindows's caption text */ void changeCaption(const QString& text); /** * Slot used to disable the UI (kposview_base widget) */ void disableUi(); void disableLogin(); /** * Slot used to enable the UI (kposview_base widget) */ void enableUi(); void enableLogin(); /** * Slot used to disable the Preferences action */ void disableConfig(); /** * Slot used to enable the Preferences action */ void enableConfig(); /** * Slot used to get selected style from the configuration list... */ void sLitemActivated(QListWidgetItem *item); /** * SLot used to update the clock on status bar */ void updateClock(); /** * Slot used to update the username on the statusbar */ void updateUserName(); /** * Slot used to update the date on the statusbar */ void updateDate(); /** * Slot used to update transaction label */ void updateTransaction(); /** * Slot used to hide the mainMenu */ void hideMenuBar(); /** * Slot used to quit the application by the admin user. */ void salir(); /** * Slot used to hide the toolbars... */ void hideToolBars(); void showToolBars(); /** * Slot used to check if the ui can be enabled **/ void reactOnLogOn(); void reactOnStartedOp(); void loadStyle(); void triggerGridAction(); void showDBConfigDialog(); void enableStartOp(); void disableStartOp(); private: void setupActions(); private: Ui::prefs_base ui_prefs_base ; Ui::store_data ui_store_data; Ui::prefs_db ui_prefs_db; Ui::pref_style ui_pref_style; Ui::pref_security ui_pref_security; Ui::pref_printers ui_pref_printers; iotposView *m_view; QLabel *labelUserInfo; QLabel *labelDate; QLabel *labelTime; QLabel *labelTransaction; protected: bool queryClose(); }; #endif // IOTPOS_H
4,752
C++
.h
155
26.393548
77
0.574672
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,865
inputdialog.h
hiramvillarreal_iotpos/src/inputdialog.h
/************************************************************************** * Copyright © 2013-2015 by Hiram R. Villarreal * * hiramvillarreal.ap@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #ifndef _InputDialog_H_ #define _InputDialog_H_ #include <QtGui> #include <klineedit.h> enum DialogType {dialogMoney=0, dialogMeasures=1, dialogTicket=3, dialogCashOut=4, dialogStockCorrection=5, dialogTerminalNum=6, dialogSpecialOrder=7, dialogTicketMsg=8, dialogCurrency=9 }; class InputDialog : public QDialog { Q_OBJECT private: QHBoxLayout *titleLayout; QGridLayout *gridLayout; QVBoxLayout *vLayout; QHBoxLayout *buttonsLayout; KLineEdit *lineEdit, *reasonEdit, *productCodeEdit; QLabel *label, *qLabel, *reasonLabel, *productCodeLabel; QLabel *lPixmap; QPushButton *buttonAccept; QPushButton *buttonCancel; DialogType dialogType; double _max, _min; public: //NOTE: in my computer, double is 8 bytes long (2^64 -1 = 1.844e^19) InputDialog(QWidget *parent=0L, bool integer=true, DialogType type=dialogMoney, QString msg="", double min=0.0, double max=18440000000000000000.0);//1.8x10^19 virtual void paint(QPainter *); double dValue; qulonglong iValue; QString reason; qulonglong getPCode() { return productCodeEdit->text().toULongLong(); } ; public slots: void setProductCode(qulonglong theCode); void setAmount(double damnt); void setAmount(int iamnt); void setProductCodeReadOnly(); protected slots: void acceptIt(); private slots: virtual void paintEvent(QPaintEvent *); }; #endif
2,886
C++
.h
58
46.5
195
0.573149
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,866
BasketEntryPriceSummary.h
hiramvillarreal_iotpos/src/nouns/BasketEntryPriceSummary.h
#ifndef BASKETENTRYPRICESUMMARY_H #define BASKETENTRYPRICESUMMARY_H #include <QString> #include <QtGlobal> #include "Currency.h" class BasketEntryPriceSummary { private: Currency net; Currency gross; Currency tax; Currency discountGross; qulonglong points; public: BasketEntryPriceSummary(double net, double gross, double tax, double discountGross, qulonglong points); BasketEntryPriceSummary(Currency net, Currency gross, Currency tax, Currency discountGross, qulonglong points); virtual ~BasketEntryPriceSummary(); QString toString(); public: //getters Currency getNet(); Currency getGross(); Currency getTax(); Currency getDiscountGross(); qulonglong getPoints(); }; #endif // BASKETENTRYPRICESUMMARY_H
767
C++
.h
25
27.24
115
0.778833
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,867
User.h
hiramvillarreal_iotpos/src/nouns/User.h
#ifndef IOTPOS_USER_H #define IOTPOS_USER_H class User { public: User(); virtual ~User(); }; class Salesman : public User { public: Salesman(); virtual ~Salesman(); }; class Customer : public User { public: Customer(); virtual ~Customer(); }; #endif //IOTPOS_USER_H
296
C++
.h
18
13.777778
30
0.676471
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,868
BasketPriceSummary.h
hiramvillarreal_iotpos/src/nouns/BasketPriceSummary.h
// // Created by krzysiek on 15.04.15. // #ifndef IOTPOS_BASKETPRICESUMMARY_H #define IOTPOS_BASKETPRICESUMMARY_H #include "BasketEntryPriceSummary.h" class BasketPriceSummary { private: Currency net; Currency gross; Currency tax; Currency discountGross; qulonglong points; public: BasketPriceSummary(); BasketPriceSummary(Currency net, Currency gross, Currency tax, Currency discountGross, qulonglong points); virtual ~BasketPriceSummary(); QString toString(); void add(BasketEntryPriceSummary basketEntryPriceSummary); public: //getters Currency getNet(); Currency getGross(); Currency getTax(); Currency getDiscountGross(); qulonglong getPoints(); }; #endif //IOTPOS_BASKETPRICESUMMARY_H
758
C++
.h
27
24.592593
110
0.769337
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,869
Currency.h
hiramvillarreal_iotpos/src/nouns/Currency.h
#ifndef CURRENCY_H #define CURRENCY_H #include <QString> #include <QTextStream> #include <QDebug> /** * @brief The Currency class * Objects of this class are mutable. Methods such as add, substract, multiply, divide are modifying * current object and returning "this" pointer to make it possible to chain calls. */ class Currency { private: long amount; public: Currency(); Currency(double amount); virtual ~Currency(); void set(Currency newValue); void set(double newValue); void substract(Currency currency); void add(Currency currency); void multiply(double multiplier); void divide(double divider); double toDouble() const; QString toString() const; }; QTextStream& operator<<(QTextStream& os, const Currency& obj); QDebug& operator<<(QDebug& os, const Currency& obj); #endif // CURRENCY_H
854
C++
.h
30
25.466667
100
0.740196
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,870
clienteditor.h
hiramvillarreal_iotpos/iotstock/src/clienteditor.h
/*************************************************************************** * Copyright (C) 2013-2015 by Hiram R. Villarreal * * hiramvillarreal.ap@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #ifndef CLIENTEDITOR_H #define CLIENTEDITOR_H #include <KDialog> #include <QtGui> #include "ui_editclient_widget.h" class ClientEditorUI : public QFrame, public Ui::clientEditor { Q_OBJECT public: ClientEditorUI( QWidget *parent=0 ); }; class ClientEditor : public KDialog { Q_OBJECT public: ClientEditor( QWidget *parent=0 ); ~ClientEditor(); void setTitle(QString t) {setCaption( t );} void setCode(QString code) { ui->editClientCode->setText(code); }; void setName(QString name) { ui->editClientName->setText(name); }; void setAddress(QString address) { ui->editClientAddress->setText(address); } ; void setPhone(QString phone) { ui->editClientPhone->setText(phone); }; void setCell(QString cell) { ui->editClientCell->setText(cell); }; void setPoints(qulonglong p) { ui->editClientPoints->setText(QString::number(p)); }; void setDiscount(double d) {ui->editClientDiscount->setText(QString::number(d)); }; void setPhoto(QPixmap photo) { ui->labelClientPhoto->setPixmap(photo); pix = photo; }; void setId(long int id) { clientId = id; }; void setSinceDate(QDate date) { ui->sinceDatePicker->setDate(date); } QString getCode(){ return ui->editClientCode->text();}; QString getName(){ return ui->editClientName->text();}; QString getAddress(){ return ui->editClientAddress->toPlainText();}; QString getPhone(){ return ui->editClientPhone->text();}; QString getCell(){ return ui->editClientCell->text();}; qulonglong getPoints() { return ui->editClientPoints->text().toULongLong(); }; double getDiscount() {return ui->editClientDiscount->text().toDouble(); } QPixmap getPhoto(){ return pix;}; QDate getSinceDate() { return ui->sinceDatePicker->date(); } private slots: void changePhoto(); void checkName(); void checkNameDelayed(); private: ClientEditorUI *ui; long int clientId; QPixmap pix; }; #endif
3,405
C++
.h
66
48.227273
90
0.582457
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,871
promoeditor.h
hiramvillarreal_iotpos/iotstock/src/promoeditor.h
/*************************************************************************** * Copyright (C) 2013-2015 by Hiram R. Villarreal * * hiramvillarreal.ap@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #ifndef PROMOEDITOR_H #define PROMOEDITOR_H #include <KDialog> #include <QDate> #include <QtGui> #include <QtSql> #include "ui_editpromo_widget.h" class PromoEditorUI : public QFrame, public Ui::promoEditor { Q_OBJECT public: PromoEditorUI( QWidget *parent=0 ); }; class PromoEditor : public KDialog { Q_OBJECT public: PromoEditor( QWidget *parent=0 ); ~PromoEditor(); QDate getDateStart() { return ui->offersDatepickerStart->date(); }; QDate getDateEnd() { return ui->offersDatepickerEnd->date(); }; double getDiscount() { return ui->spinboxDiscount->value(); }; void setDb(QSqlDatabase database); void populateCategoriesCombo(); void setupModel(); bool isProductSelected(); qulonglong getSelectedProductCode(); private slots: void checkValid(); void setFilter(); void productChanged(); void discountChanged(); void priceChanged(); private: PromoEditorUI *ui; QSqlDatabase db; QSqlRelationalTableModel *model; }; #endif
2,520
C++
.h
58
40.482759
77
0.533007
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,872
providerseditor.h
hiramvillarreal_iotpos/iotstock/src/providerseditor.h
/************************************************************************** * Copyright © 2007-2011 by Miguel Chavez Gamboa * * miguel@lemonpos.org * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #ifndef PROVIDERSEDITOR_H #define PROVIDERSEDITOR_H #include <KDialog> #include <QDate> #include <QtGui> #include <QPixmap> #include <QtSql> #include "ui_providerseditor.h" class MibitFloatPanel; class MibitTip; #include "../../src/structs.h" class ProvidersEditorUI : public QFrame, public Ui::providersEditor { Q_OBJECT public: ProvidersEditorUI( QWidget *parent=0 ); }; class ProvidersEditor : public KDialog { Q_OBJECT public: ProvidersEditor( QWidget *parent=0, bool newProvider = false, const QSqlDatabase& database=QSqlDatabase() ); ~ProvidersEditor(); ProviderInfo getProviderInfo() { return m_pInfo; }; void setDb(QSqlDatabase database); void setProviderId(qulonglong id); private slots: void addItem(); void removeItem(); void setupModel(); void checkFieldsState(); protected slots: virtual void slotButtonClicked(int button); private: ProvidersEditorUI *ui; QSqlDatabase db; ProviderInfo m_pInfo; MibitFloatPanel *panel; QSqlRelationalTableModel *m_model, *m_model2; bool modelCreated; }; #endif
2,563
C++
.h
61
39.508197
112
0.556225
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,874
subcategoryeditor.h
hiramvillarreal_iotpos/iotstock/src/subcategoryeditor.h
/*************************************************************************** * Copyright (C) 2012 by Miguel Chavez Gamboa * * hiramvillarreal.ap@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #ifndef SUBCATEGORYEDITOR_H #define SUBCATEGORYEDITOR_H #include <KDialog> #include <QDate> #include <QtGui> #include <QtSql> #include "ui_subcategoryeditor.h" class SubcategoryEditorUI : public QFrame, public Ui::subcategoryEditor { Q_OBJECT public: SubcategoryEditorUI( QWidget *parent=0 ); }; class SubcategoryEditor : public KDialog { Q_OBJECT public: SubcategoryEditor( QWidget *parent=0 ); ~SubcategoryEditor(); void setLabelForName(QString text) { ui->lblName->setText(text); }; void setLabelForList(QString text) { ui->lblChildText->setText(text); }; void setName(QString n) { ui->editName->setText(n); }; void disableAddButton(bool y) { ui->btnAdd->setDisabled(y); }; void setDb(QSqlDatabase d); void setDialogType(int t); void setCatList(QStringList c) { catList = c; }; void setScatList(QStringList s) { scatList = s; }; QStringList getChildren(); QString getName() { return ui->editName->text(); }; void populateList(QStringList list, QStringList checkedList=QStringList() ); void hideListView() { ui->listView->hide(); ui->lblChildText->hide(); ui->btnAdd->hide(); }; private slots: void checkValid(); void addNewChild(); //for adding a new category or subcategory, depending on the dialog use. private: SubcategoryEditorUI *ui; QSqlDatabase db; int dialogType; QStringList catList; QStringList scatList; }; #endif
2,972
C++
.h
61
45.491803
99
0.554787
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,875
iotstockview.h
hiramvillarreal_iotpos/iotstock/src/iotstockview.h
/*************************************************************************** * Copyright © 2007-2012 by Miguel Chavez Gamboa * * hiramvillarreal.ap@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #ifndef IOTSTOCKVIEW_H #define IOTSTOCKVIEW_H #include <QWidget> #include <QtSql> #include "ui_iotstockview_base.h" #include "../../src/loginwindow.h" class QPainter; class LoginWindow; class KPlotObject; class MibitFloatPanel; class QListWidgetItem; class MibitNotifier; /** * This is the main view class for iotstock. Most of the non-menu, * non-toolbar, and non-statusbar (e.g., non frame) GUI code should go * here. * * @short Main view * @author Miguel Chavez Gamboa <miguel.chavez.gamboa@gmail.com> */ class iotstockView : public QWidget, public Ui::iotstockview_base { Q_OBJECT public: iotstockView(QWidget *parent); virtual ~iotstockView(); bool isConnected() { return db.isOpen(); }; bool modelsAreCreated() { return modelsCreated; }; void closeDB(); void openDB(); bool isAdminUser() { return adminIsLogged; } private: QTimer *rmTimer; Ui::iotstockview_base ui_mainview; QString activeDb; QSqlDatabase db; bool adminIsLogged; LoginWindow *dlgPassword; QHash<QString, int> categoriesHash; QHash<QString, int> cardTypesHash; QHash<QString, int> departmentsHash; QHash<QString, int> subcategoriesHash; QSqlRelationalTableModel *productsModel; QSqlRelationalTableModel *offersModel; QSqlRelationalTableModel *cashflowModel; QSqlRelationalTableModel *specialOrdersModel; QSqlTableModel *usersModel; QSqlTableModel *measuresModel; QSqlTableModel *categoriesModel; QSqlTableModel *departmentsModel; QSqlRelationalTableModel *subcategoriesModel; QSqlTableModel *balancesModel; QSqlTableModel *clientsModel; QSqlTableModel *randomMsgModel; QSqlRelationalTableModel *reservationsModel; QSqlRelationalTableModel *logsModel; QSqlRelationalTableModel *transactionsModel; QSqlTableModel *currenciesModel; int productCodeIndex, productDescIndex, productPriceIndex, productStockIndex, productCostIndex, productSoldUnitsIndex, productLastSoldIndex, productUnitsIndex, productTaxIndex, productETaxIndex, productPhotoIndex, productCategoryIndex, productPointsIndex, productLastProviderIndex, productAlphaCodeIndex, productIsAGroupIndex, productIsARawIndex, productGEIndex, productIsNotDiscountable; int offerIdIndex, offerDiscountIndex, offerDateStartIndex, offerDateEndIndex,offerProdIdIndex; int userIdIndex, usernameIndex, nameIndex, passwordIndex, saltIndex, addressIndex, phoneIndex, cellIndex, roleIndex, photoIndex; int transIdIndex, transClientidIndex, transTypeIndex,transAmountIndex,transDateIndex,transTimeIndex,transPaidWithIndex, transChangeGivenIndex,transPayMethodIndex,transStateIndex,transUseridIndex,transCardNumIndex,transItemCountIndex,transPointsIndex, transDiscMoneyIndex,transDiscIndex,transCardAuthNumberIndex,transUtilityIndex,transTerminalNumIndex,transItemsListIndex, transSOIndex, transProvIdIndex; QTimer *timerCheckDb, *timerUpdateGraphs; int balanceIdIndex, balanceDateEndIndex, balanceUserNameIndex, balanceInitAmountIndex, balanceInIndex, balanceOutIndex, balanceCashIndex, balanceCardIndex,balanceTransIndex, balanceTerminalNumIndex, balanceDateStartIndex, balanceUseridIndex; int cashflowIdIndex, cashflowDateIndex, cashflowTimeIndex, cashflowUseridIndex, cashflowReasonIndex, cashflowAmountIndex, cashflowTerminalNumIndex, cashflowTypeIndex; int counter; bool modelsCreated,graphSoldItemsCreated; KPlotObject *objProfit, *objSales, *objMostSold, *objMostSoldB; MibitFloatPanel *fpFilterTrans, *fpFilterProducts, *fpFilterBalances, *fpFilterOffers, *fpFilterSpecialOrders; QListWidgetItem *itmEndOfMonth; QListWidgetItem *itmGralEndOfDay; QListWidgetItem *itmEndOfDay; QListWidgetItem *itmPrintSoldOutProducts; QListWidgetItem *itmPrintLowStockProducts; QListWidgetItem *itmPrintStock; //QListWidgetItem *itmPrintBalance; MibitNotifier *notifierPanel; qulonglong loggedUserId; signals: void signalChangeStatusbar(const QString& text); void signalChangeCaption(const QString& text); void signalConnected(); void signalDisconnected(); void signalConnectActions(); void signalShowPrefs(); void signalAdminLoggedOn(); void signalSupervisorLoggedOn(); void signalAdminLoggedOff(); void signalSalir(); void signalShowDbConfig(); private slots: /* Ui related slot */ void login(); void settingsChanged(); void settingsChangedOnInitConfig(); void setupSignalConnections(); void setOffersFilter(); void toggleFilterBox(bool show); void showProductsPage(); void showOffersPage(); void showUsersPage(); void showMeasuresPage(); void showCategoriesPage(); void showDepartmentsPage(); void showSubCategoriesPage(); void showClientsPage(); void showTransactionsPage(); void showReports(); void showRandomMsgs(); void usersViewOnSelected(const QModelIndex & index); void productsViewOnSelected(const QModelIndex &index); void clientsViewOnSelected(const QModelIndex &index); void doPurchase(); void stockCorrection(); void adjustOffersTable(); void showPrefs(); void cleanErrorLabel(); void showWelcomeGraphs(); void setupGraphs(); void updateGraphs(); void disableUI(); void enableUI(); void doEmitSignalSalir(); void updateDepartmentsCombo(); void updateCategoriesCombo(); void updateCardTypesCombo(); void updateSubCategoriesCombo(); void showProdListAsGrid(); void showProdListAsTable(); void adjustProductsTable(); void showBalancesPage(); void setupBalancesModel(); void showCashFlowPage(); void showSpecialOrders(); void setupCashFlowModel(); void setupSpecialOrdersModel(); void setSpecialOrdersFilter(); void setupRandomMsgModel(); void showCurrencies(); void reportActivated(QListWidgetItem *); void printGralEndOfDay(); void printEndOfDay(); void printEndOfMonth(); void printLowStockProducts(); void printSoldOutProducts(); void printStock(); void printSelectedBalance(); /* DB slots */ void createUser(); void createOffer(); void createProduct(); void createMeasure(); void createCategory(); void createDepartment(); void createSubCategory(); void createClient(); void createRandomMsg(); void createCurrency(); void deleteSelectedCurrency(); void deleteSelectedOffer(); void deleteSelectedUser(); void deleteSelectedProduct(); void deleteSelectedMeasure(); void deleteSelectedDepartment(); void deleteSelectedCategory(); void deleteSelectedSubCategory(); void deleteSelectedClient(); void populateDepartmentsHash(); void populateCategoriesHash(); void populateCardTypesHash(); void populateSubCategoriesHash(); void setProductsFilter(); void setTransactionsFilter(); void setBalancesFilter(); void correctStock(qulonglong code, double oldStock, double newStock, const QString &reason); TransactionInfo createPurchase(ProductInfo info); void setupDb(); void setupUsersModel(); void setupOffersModel(); void setupProductsModel(); void setupMeasuresModel(); void setupCategoriesModel(); void setupDepartmentsModel(); void setupSubCategoriesModel(); void setupClientsModel(); void setupTransactionsModel(); void setupCurrenciesModel(); void checkDBStatus(); void connectToDb(); //Biel - export products void exportTable(); void exportQTableView(QAbstractItemView *tableview); //LOGS void log(const qulonglong &uid, const QDate &date, const QTime &time, const QString &text); void showLogs(); void setupLogsModel(); //reservations void showReservations(); void setupReservationsModel(); void reservationsOnSelected(const QModelIndex &index); void createFloatingPanels(); void reSelectModels(); void checkDefaultView(); void departmentsOnSelected(const QModelIndex &index); void categoriesOnSelected(const QModelIndex &index); }; #endif // IOTSTOCKVIEW_H
9,502
C++
.h
231
37.203463
245
0.727853
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,876
producteditor.h
hiramvillarreal_iotpos/iotstock/src/producteditor.h
/*************************************************************************** * Copyright (C) 2013-2015 by Hiram R. Villarreal * * hiramvillarreal.ap@gmail.com * * Modified by Daniel A. Cervantes dcchivela@gmail.com * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #ifndef PRODUCTEDITOR_H #define PRODUCTEDITOR_H #include <KDialog> #include <QDate> #include <QtGui> #include <QPixmap> #include <QtSql> #include "ui_producteditor.h" class MibitFloatPanel; class MibitTip; #include "../../src/structs.h" enum returnType {statusNormal=998, statusMod=999}; class ProductEditorUI : public QFrame, public Ui::productEditor { Q_OBJECT public: ProductEditorUI( QWidget *parent=0); private slots: void on_chRise_clicked(bool checked); }; class ProductEditor : public KDialog { Q_OBJECT public: ProductEditor( QWidget *parent=0, bool newProduct = false ); ~ProductEditor(); qulonglong getCode() { return ui->editCode->text().toULongLong(); }; QString getAlphacode() { return ui->editAlphacode->text(); }; QString getVendorcode() { return ui->editVendorcode->text(); }; QString getDescription() { return ui->editDesc->text(); }; double getStockQty() { return ui->editStockQty->text().toDouble(); }; int getDepartmentId(); int getCategoryId(); int getSubCategoryId(); int getSubCategoryParent(); int getMeasureId(); QString getDepartmentStr(int c); QString getCategoryStr(int c); QString getSubCategoryStr(int c); QString getMeasureStr(int c); double getCost() { return ui->editCost->text().toDouble(); }; double getTax1() { return ui->editTax->text().toDouble(); }; double getTax2() { return ui->editExtraTaxes->text().toDouble(); }; double getPrice() { return ui->editFinalPrice->text().toDouble(); }; qulonglong getPoints() { return ui->editPoints->text().toULongLong(); }; QPixmap getPhoto() { qDebug()<<"pixmap Size:"<<pix.size(); return pix; }; QString getReason() { return reason; }; bool isCorrectingStock() {return correctingStockOk;}; double getOldStock() { return oldStockQty; }; double getGRoupStockMax(); double getGroupPriceDrop() { return groupInfo.priceDrop; }; void setStockQtyReadOnly(bool enabled) { ui->editStockQty->setReadOnly(enabled); }; void setAutoCode(bool yes) { autoCode = yes;}; void populateDepartmentsCombo(); void populateCategoriesCombo(); void populateSubCategoriesCombo(); void populateMeasuresCombo(); void calculateGroupValues(); void setDb(QSqlDatabase database); void setCode(qulonglong c) {ui->editCode->setText(QString::number(c)); }; void setAlphacode(QString c) { ui->editAlphacode->setText(c); }; void setVendorcode(QString c) { ui->editVendorcode->setText(c); }; void setDescription(QString d) {ui->editDesc->setText(d); }; void setStockQty(double q) {ui->editStockQty->setText(QString::number(q)); }; void setDepartment(QString str); void setDepartment(int i); void setCategory(QString str); void setCategory(int i); void setSubCategory(int i); void setSubCategory(QString str); void setSubCategoryParent(int parentId); void setMeasure(QString str); void setMeasure(int i); void setCost(double c) {ui->editCost->setText(QString::number(c)); }; void setTax1(double t) {ui->editTax->setText(QString::number(t)); }; void setTax2(double t) {ui->editExtraTaxes->setText(QString::number(t)); }; void setPrice(double p) {ui->editFinalPrice->setText(QString::number(p)); }; void setPoints(qulonglong p) {ui->editPoints->setText(QString::number(p)); }; void setPhoto(QPixmap p); void setIsAGroup(bool value); void setIsARaw(bool value); void setGroupElements(ProductInfo pi); void disableCode() { ui->editCode->setReadOnly(true); modifyCode=false; }; void enableCode() { ui->editCode->setReadOnly(false); modifyCode=true;}; void disableStockCorrection() { ui->btnStockCorrect->hide(); } void setModel(QSqlRelationalTableModel *model); GroupInfo getGroupHash(); QString getGroupElementsStr(); bool isGroup(); bool isRaw(); bool isNotDiscountable(); bool hasUnlimitedStock(); private slots: void changePhoto(); void changeCode(); void modifyStock(); void calculatePrice(); void calculateProfit(QString amountStr); void checkIfCodeExists(); void checkFieldsState(); void toggleGroup(bool checked); void toggleRaw(bool checked); void applyFilter(const QString &text); void applyFilter(); void addItem(); void removeItem(); void itemDoubleClicked(QTableWidgetItem* item); void updatePriceDrop(double value); void setNotDiscountable(bool value); void setUnlimitedStock(bool value); qulonglong getNextCode(); void verifyVendorcodeDuplicates(); void verifyAlphacodeDuplicates(); void modifyDepartment(); void modifyCategory(); void createNewSubcategory(); void createNewCategory(); void createNewDepartment(); void createNewMeasure(); void printBarcode(); protected slots: virtual void slotButtonClicked(int button); private: ProductEditorUI *ui; QSqlDatabase db; QPixmap pix; returnType status; bool modifyCode; bool autoCode; double oldStockQty; QString reason; bool correctingStockOk; GroupInfo groupInfo; bool m_modelAssigned; QSqlRelationalTableModel *m_model; MibitFloatPanel *groupPanel; MibitTip *errorPanel; MibitTip *errorAlphacode; MibitTip *errorVendorcode; }; #endif
7,187
C++
.h
160
40.64375
94
0.623444
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,877
usereditor.h
hiramvillarreal_iotpos/iotstock/src/usereditor.h
/*************************************************************************** * Copyright (C) 2013-2015 by Hiram R. Villarreal * * hiramvillarreal.ap@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #ifndef USEREDITOR_H #define USEREDITOR_H #include <KDialog> #include <QtGui> #include "ui_edituser_widget.h" class UserEditorUI : public QFrame, public Ui::userEditor { Q_OBJECT public: UserEditorUI( QWidget *parent=0 ); }; class UserEditor : public KDialog { Q_OBJECT public: UserEditor( QWidget *parent=0 ); ~UserEditor(); void setUserName(QString uname); void setRealName(QString rname) { ui->editUsersName->setText(rname); }; void setAddress(QString address) { ui->editUsersAddress->setText(address); } ; void setPhone(QString phone) { ui->editUsersPhone->setText(phone); }; void setCell(QString cell) { ui->editUsersCell->setText(cell); }; void setPhoto(QPixmap photo) { ui->labelUsersPhoto->setPixmap(photo); pix = photo; }; void setId(long int id) { userId = id; }; void setUserRole(const int &role); void disableRoles(const bool &yes) {ui->groupRoles->setDisabled(yes);}; void disallowAdminChange(const bool &yes); QString getUserName(){ return ui->editUsersUsername->text();}; QString getRealName(){ return ui->editUsersName->text();}; QString getAddress(){ return ui->editUsersAddress->toPlainText();}; QString getPhone(){ return ui->editUsersPhone->text();}; QString getCell(){ return ui->editUsersCell->text();}; QString getNewPassword() { return ui->editUsersPassword->text(); }; QPixmap getPhoto(){ return pix;}; int getUserRole(); private slots: void changePhoto(); void checkName(); private: UserEditorUI *ui; long int userId; QPixmap pix; }; #endif
3,058
C++
.h
63
45.269841
89
0.567314
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,878
purchaseeditor.h
hiramvillarreal_iotpos/iotstock/src/purchaseeditor.h
/*************************************************************************** * Copyright (C) 2013-2015 by Hiram R. Villarreal * * hiramvillarreal.ap@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #ifndef PURCHASEEDITOR_H #define PURCHASEEDITOR_H #include <KDialog> #include <QDate> #include <QtGui> #include <QPixmap> #include <QtSql> #include "../../src/structs.h" #include "../../src/misc.h" #include "ui_purchaseeditor.h" enum rType {estatusNormal=899, estatusMod=999}; class MibitTip; class PurchaseEditorUI : public QFrame, public Ui::purchaseEditor { Q_OBJECT public: PurchaseEditorUI( QWidget *parent=0 ); }; class PurchaseEditor : public KDialog { Q_OBJECT public: PurchaseEditor( QWidget *parent=0 ); ~PurchaseEditor(); qulonglong getCode() { return ui->editCode->text().toULongLong(); }; // this will be deprecated when using the vendor code which is STR. QString getCodeStr() { return ui->editCode->text(); }; QString getDescription() { return ui->editDesc->text(); }; double getPurchaseQty(); int getDepartmentId(); int getCategoryId(); int getSubCategoryId(); int getMeasureId(); QString getDepartmentStr(int c); QString getCategoryStr(int c); QString getSubCategoryStr(int c); QString getMeasureStr(int c); double getCost() { return ui->editCost->text().toDouble(); }; double getTax1() { return ui->editTax->text().toDouble(); }; double getTax2() { return ui->editExtraTaxes->text().toDouble(); }; double getPrice() { return ui->editFinalPrice->text().toDouble(); }; double getProfit() { return ui->editUtility->text().toDouble(); }; double getQtyOnDb() { return qtyOnDb; } qulonglong getPoints() { return ui->editPoints->text().toULongLong(); }; QPixmap getPhoto() { return pix; }; QByteArray getPhotoBA() { return Misc::pixmap2ByteArray(new QPixmap(pix)); }; QHash<qulonglong, ProductInfo> getHash() { return productsHash; }; double getTotalBuy() { return totalBuy; }; double getItemCount() { return itemCount; }; double getTotalTaxes() { return totalTaxes; }; QString getAlphacode() { return ui->editAlphacode->text(); } QString getVendorcode() { return ui->editVendorcode->text(); } void populateDepartmentsCombo(); void populateCategoriesCombo(); void populateSubCategoriesCombo(); void populateMeasuresCombo(); void setDb(QSqlDatabase database); void setCode(qulonglong c) {ui->editCode->setText(QString::number(c)); }; void setCode(QString c) {ui->editCode->setText(c); } void setDescription(QString d) {ui->editDesc->setText(d); }; void setPurchaseQty(double q) {ui->editQty->setText(QString::number(q)); }; void setDepartment(QString str); void setDepartment(int i); void setCategory(QString str); void setCategory(int i); void setSubCategory(QString str); void setSubCategory(int i); void setMeasure(QString str); void setMeasure(int i); void setCost(double c) {ui->editCost->setText(QString::number(c)); }; void setTax1(double t) {ui->editTax->setText(QString::number(t)); }; void setTax2(double t) {ui->editExtraTaxes->setText(QString::number(t)); }; void setPrice(double p) {ui->editFinalPrice->setText(QString::number(p)); }; void setPoints(qulonglong p) {ui->editPoints->setText(QString::number(p)); }; void setPhoto(QPixmap p) {ui->labelPhoto->setPixmap(p); pix=p; }; void setIsAGroup(bool value); void disableCode() { ui->editCode->setReadOnly(true); }; void enableCode() { ui->editCode->setReadOnly(false); }; void resetEdits(); private slots: void changePhoto(); void calculatePrice(); void timerCheck(); void justCheck(); void checkIfCodeExists(); void addItemToList(); void setupTable(); void focusItemsPerBox(bool set); void deleteSelectedItem(); void insertProduct(ProductInfo info); void modifyCategory(); void modifyDepartment(); void createNewDepartment(); void createNewSubcategory(); void createNewCategory(); void createNewMeasure(); protected slots: virtual void slotButtonClicked(int button); private: PurchaseEditorUI *ui; QSqlDatabase db; QPixmap pix; rType status; double qtyOnDb; bool productExists; double totalBuy; double itemCount; double totalTaxes; QString gelem; QHash<qulonglong, ProductInfo> productsHash; QString lastCode; MibitTip *errorPanel; }; #endif
6,068
C++
.h
132
41.954545
144
0.599324
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,879
offersdelegate.h
hiramvillarreal_iotpos/iotstock/src/offersdelegate.h
/*************************************************************************** * Copyright (C) 2007-2007-2009 by Miguel Chavez Gamboa * * hiramvillarreal.ap@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #ifndef OFFERSDELEGATE_H #define OFFERSDELEGATE_H #include <QModelIndex> #include <QSqlRelationalDelegate> class OffersDelegate : public QSqlRelationalDelegate { Q_OBJECT public: OffersDelegate(QObject *parent = 0); void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const; QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const; }; #endif
1,932
C++
.h
32
57.875
112
0.50792
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,880
iotstock.h
hiramvillarreal_iotpos/iotstock/src/iotstock.h
/*************************************************************************** * Copyright (C) 2013-2015 by Hiram R. Villarreal * * hiramvillarreal.ap@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #ifndef IOTSTOCK_H #define IOTSTOCK_H #include "ui_prefs_base.h" #include "ui_prefs_db.h" #include "ui_pref_printers.h" #include <kxmlguiwindow.h> #include <QDragEnterEvent> #include <QDropEvent> class KLed; class KToggleAction; class iotstockView; class QPrinter; class QTimer; /** * This class serves as the main window for iotstock. It handles the * menus, toolbars, and status bars. * * @short Main window class * @author Miguel Chavez Gamboa <miguel.chavez.gamboa@gmail.com> * @version 0.1 */ class iotstock : public KXmlGuiWindow { Q_OBJECT public: /** * Default Constructor */ iotstock(); /** * Default Destructor */ virtual ~iotstock(); //public Q_SLOTS: private slots: void optionsPreferences(); void changeCaption(const QString& text); void changeStatusbar(const QString& text); void setConnection(bool yes); void setConnected(); void setDisconnected(); void enableUI(); void disableUI(); void salir(); void loadStyle(); void showDBConfigDialog(); void fixGeom(); void hideMenuBar(); private: void setupActions(); private: iotstockView *m_view; Ui::prefs_base ui_prefs_base ; Ui::prefs_db ui_prefs_db; Ui::pref_printers ui_pref_printers; KLed *led; QTimer *timer; QPrinter *m_printer; protected: bool queryClose(); }; #endif // IOTSTOCK_H
2,873
C++
.h
81
32.283951
77
0.554152
hiramvillarreal/iotpos
146
77
17
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,888
sonicsaudio.h
syams86_Virtual-Audio-Pipeline/Virtual Audio Pipeline/sonicsaudio.h
/* Module Name: sonicsaudio.h Abstract: Header file for common stuff. */ #ifndef __SONICSAUDIO_H_ #define __SONICSAUDIO_H_ #include <portcls.h> #include <stdunk.h> #include <ksdebug.h> #include "kshelper.h" //============================================================================= // Defines //============================================================================= // Version number. Revision numbers are specified for each sample. #define SONICSAUDIO_VERSION 1 #define SONICSAUDIO_REVISION 0 // Product Id // {5B722BF8-F0AB-47ee-B9C8-8D61D31375A1} #define STATIC_PID_SONICSAUDIO 0x5b722bf8, 0xf0ab, 0x47ee, 0xb9, 0xc8, 0x8d, 0x61, 0xd3, 0x13, 0x75, 0xa1 DEFINE_GUIDSTRUCT("5B722BF8-F0AB-47ee-B9C8-8D61D31375A1", PID_SONICSAUDIO); #define PID_SONICSAUDIO DEFINE_GUIDNAMED(PID_SONICSAUDIO) // Name Guid // {946A7B1A-EBBC-422a-A81F-F07C8D40D3B4} #define STATIC_NAME_SONICSAUDIO 0x946a7b1a, 0xebbc, 0x422a, 0xa8, 0x1f, 0xf0, 0x7c, 0x8d, 0x40, 0xd3, 0xb4 DEFINE_GUIDSTRUCT("946A7B1A-EBBC-422a-A81F-F07C8D40D3B4", NAME_SONICSAUDIO); #define NAME_SONICSAUDIO DEFINE_GUIDNAMED(NAME_SONICSAUDIO) // Pool tag used for MSVAD allocations #define SONICSAUDIO_POOLTAG 'INOS' // Debug module name #define STR_MODULENAME "SONICSAudio: " // Debug utility macros #define D_FUNC 4 #define D_BLAB DEBUGLVL_BLAB #define D_VERBOSE DEBUGLVL_VERBOSE #define D_TERSE DEBUGLVL_TERSE #define D_ERROR DEBUGLVL_ERROR #define DPF _DbgPrintF #define DPF_ENTER(x) DPF(D_FUNC, x) // Channel orientation #define CHAN_LEFT 0 #define CHAN_RIGHT 1 #define CHAN_MASTER (-1) // Pin properties. #define MAX_OUTPUT_STREAMS 1 // Number of capture streams. #define MAX_INPUT_STREAMS 1 // Number of render streams. #define MAX_TOTAL_STREAMS MAX_OUTPUT_STREAMS + MAX_INPUT_STREAMS // PCM Info [6,6,8,32,8000,192000] #define MIN_CHANNELS 8 // Min Channels. #define MAX_CHANNELS_PCM 8 // Max Channels. #define MIN_BITS_PER_SAMPLE_PCM 8 // Min Bits Per Sample #define MAX_BITS_PER_SAMPLE_PCM 32 // Max Bits Per Sample #define MIN_SAMPLE_RATE 8000 // Min Sample Rate #define MAX_SAMPLE_RATE 192000 // Max Sample Rate // Dma Settings. #define DMA_BUFFER_SIZE 0x32000 #define TRAN_BUFFER_SIZE DMA_BUFFER_SIZE #define KSPROPERTY_TYPE_ALL KSPROPERTY_TYPE_BASICSUPPORT | \ KSPROPERTY_TYPE_GET | \ KSPROPERTY_TYPE_SET // Specific node numbers for vrtaupipe.sys #define DEV_SPECIFIC_VT_BOOL 9 #define DEV_SPECIFIC_VT_I4 10 #define DEV_SPECIFIC_VT_UI4 11 //============================================================================= // Enumerations //============================================================================= // Wave pins enum { KSPIN_WAVE_CAPTURE_SINK = 0, KSPIN_WAVE_CAPTURE_SOURCE, KSPIN_WAVE_RENDER_SINK, KSPIN_WAVE_RENDER_SOURCE }; // Wave Topology nodes. enum { KSNODE_WAVE_ADC = 0, KSNODE_WAVE_DAC }; // topology pins. enum { KSPIN_TOPO_WAVEOUT_SOURCE = 0, //KSPIN_TOPO_SYNTHOUT_SOURCE, //KSPIN_TOPO_SYNTHIN_SOURCE, KSPIN_TOPO_MIC_SOURCE, KSPIN_TOPO_LINEOUT_DEST, KSPIN_TOPO_WAVEIN_DEST }; // topology nodes. enum { KSNODE_TOPO_WAVEOUT_VOLUME = 0, KSNODE_TOPO_WAVEOUT_MUTE, //KSNODE_TOPO_SYNTHOUT_VOLUME, //KSNODE_TOPO_SYNTHOUT_MUTE, KSNODE_TOPO_MIC_VOLUME, //KSNODE_TOPO_SYNTHIN_VOLUME, KSNODE_TOPO_LINEOUT_MIX, KSNODE_TOPO_LINEOUT_VOLUME, KSNODE_TOPO_WAVEIN_MUX }; //============================================================================= // Typedefs //============================================================================= // Connection table for registering topology/wave bridge connection typedef struct _PHYSICALCONNECTIONTABLE { ULONG ulTopologyIn; ULONG ulTopologyOut; ULONG ulWaveIn; ULONG ulWaveOut; } PHYSICALCONNECTIONTABLE, *PPHYSICALCONNECTIONTABLE; //============================================================================= // Externs //============================================================================= // Physical connection table. Defined in mintopo.cpp for each sample extern PHYSICALCONNECTIONTABLE TopologyPhysicalConnections; // Generic topology handler extern NTSTATUS PropertyHandler_Topology(IN PPCPROPERTY_REQUEST PropertyRequest); // Generic wave port handler extern NTSTATUS PropertyHandler_Wave(IN PPCPROPERTY_REQUEST PropertyRequest); // Default WaveFilter automation table. // Handles the GeneralComponentId request. extern NTSTATUS PropertyHandler_WaveFilter(IN PPCPROPERTY_REQUEST PropertyRequest); #endif
5,038
C++
.h
128
36.328125
106
0.592092
syams86/Virtual-Audio-Pipeline
128
38
11
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,891
kshelper.h
syams86_Virtual-Audio-Pipeline/Virtual Audio Pipeline/kshelper.h
/* Module Name: kshelper.h Abstract: Helper functions for msvad */ #ifndef __KSHELPER_H_ #define __KSHELPER_H_ #include <portcls.h> #include <ksdebug.h> PWAVEFORMATEX GetWaveFormatEx(IN PKSDATAFORMAT pDataFormat); NTSTATUS PropertyHandler_BasicSupport(IN PPCPROPERTY_REQUEST PropertyRequest, IN ULONG Flags, IN DWORD PropTypeSetId); NTSTATUS ValidatePropertyParams(IN PPCPROPERTY_REQUEST PropertyRequest, IN ULONG cbValueSize, IN ULONG cbInstanceSize = 0); #endif
473
C++
.h
14
32.142857
123
0.828194
syams86/Virtual-Audio-Pipeline
128
38
11
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,892
common.h
syams86_Virtual-Audio-Pipeline/Virtual Audio Pipeline/common.h
/* Module Name: Common.h Abstract: CAdapterCommon class declaration. */ #ifndef __COMMON_H_ #define __COMMON_H_ //============================================================================= // Defines //============================================================================= DEFINE_GUID(IID_IAdapterCommon, 0x7eda2950, 0xbf9f, 0x11d0, 0x87, 0x1f, 0x0, 0xa0, 0xc9, 0x11, 0xb5, 0x44); //============================================================================= // Interfaces //============================================================================= /////////////////////////////////////////////////////////////////////////////// // IAdapterCommon DECLARE_INTERFACE_(IAdapterCommon, IUnknown) { STDMETHOD_(NTSTATUS, Init) ( THIS_ IN PDEVICE_OBJECT DeviceObject ) PURE; STDMETHOD_(PDEVICE_OBJECT, GetDeviceObject) ( THIS ) PURE; STDMETHOD_(VOID, SetWaveServiceGroup) ( THIS_ IN PSERVICEGROUP ServiceGroup ) PURE; STDMETHOD_(PUNKNOWN *, WavePortDriverDest) ( THIS ) PURE; STDMETHOD_(BOOL, bDevSpecificRead)( THIS_ ) PURE; STDMETHOD_(VOID, bDevSpecificWrite)( THIS_ IN BOOL bDevSpecific ); STDMETHOD_(INT, iDevSpecificRead) ( THIS_ ) PURE; STDMETHOD_(VOID, iDevSpecificWrite) ( THIS_ IN INT iDevSpecific ); STDMETHOD_(UINT, uiDevSpecificRead) ( THIS_ ) PURE; STDMETHOD_(VOID, uiDevSpecificWrite) ( THIS_ IN UINT uiDevSpecific ); STDMETHOD_(BOOL, MixerMuteRead) ( THIS_ IN ULONG Index ) PURE; STDMETHOD_(VOID, MixerMuteWrite) ( THIS_ IN ULONG Index, IN BOOL Value ); STDMETHOD_(ULONG, MixerMuxRead) ( THIS ); STDMETHOD_(VOID, MixerMuxWrite) ( THIS_ IN ULONG Index ); STDMETHOD_(LONG, MixerVolumeRead) ( THIS_ IN ULONG Index, IN LONG Channel ) PURE; STDMETHOD_(VOID, MixerVolumeWrite) ( THIS_ IN ULONG Index, IN LONG Channel, IN LONG Value ) PURE; STDMETHOD_(VOID, MixerReset) ( THIS ) PURE; }; typedef IAdapterCommon *PADAPTERCOMMON; //============================================================================= // Function Prototypes //============================================================================= NTSTATUS NewAdapterCommon( OUT PUNKNOWN * Unknown, IN REFCLSID, IN PUNKNOWN UnknownOuter OPTIONAL, IN POOL_TYPE PoolType ); #endif //_COMMON_H_
2,280
C++
.h
47
46.297872
107
0.544514
syams86/Virtual-Audio-Pipeline
128
38
11
GPL-2.0
9/20/2024, 9:42:13 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false