commit ec1fdaa08298c0c6bdb108eafd885b98b590cfae
parent 4c475a43d49d79fccd8a119384e447dce61b88cf
Author: Christian Grothoff <christian@grothoff.org>
Date: Thu, 5 Jun 2025 11:02:27 +0200
add Debian package, fix problems with stdout, terminate on CTRL-D/eof, instead of 'quit' input
Diffstat:
54 files changed, 2888 insertions(+), 2161 deletions(-)
diff --git a/.gitignore b/.gitignore
@@ -0,0 +1,11 @@
+**~
+robocop.cabal
+stack.yaml.lock
+.stack-work/
+debian/.debhelper/
+debian/robocop/
+debian/robocop.substvars
+debian/tmp/
+debian/files
+debian/debhelper-build-stamp
+debian/.debhelper
diff --git a/CHANGELOG.md b/CHANGELOG.md
@@ -5,7 +5,7 @@ SPDX-License-Identifier: AGPL-3.0-or-later
SPDX-License-Identifier: EUPL-1.2
-->
-# Changelog for `kyc`
+# Changelog for `robocop`
All notable changes to this project will be documented in this file.
@@ -25,4 +25,3 @@ Development version. Includes:
- JSON input and output
- Dhall config file
- 82 test files
-
diff --git a/README.md b/README.md
@@ -5,15 +5,15 @@ SPDX-License-Identifier: AGPL-3.0-or-later
SPDX-License-Identifier: EUPL-1.2
-->
-# KYCheck
+# Robocop
-KYCheck is a Counter Terrorist Financing (CTF) sanction processing tool written in Haskell. It can be used for compliance processes in software such as [GNU Taler](https://taler.net).
+Robocop is a Counter Terrorist Financing (CTF) sanction processing tool written in Haskell. It can be used for compliance processes in software such as [GNU Taler](https://taler.net).
The most recent [XML sanction list](https://www.sesam.search.admin.ch/sesam-search-web/pages/downloadXmlGesamtliste.xhtml?lang=en&action=downloadXmlGesamtlisteAction) should be [downloaded](https://www.sesam.search.admin.ch/sesam-search-web/pages/downloadXmlGesamtliste.xhtml?lang=en&action=downloadXmlGesamtlisteAction) from the Swiss [State Secretariat for Economic Affairs](https://www.seco.admin.ch/) (SECO). In the future additional sanction lists can be added.
## Prepare for installation
-Download the repository containing all the [source files](https://git.disroot.org/lnrs/kycheck)
+Download the repository containing all the [source files](https://git.taler.net/robocop.git/)
Then make sure you have [The Haskell Tool Stack](https://docs.haskellstack.org/en/stable/install_and_upgrade/) installed. When using [Nix](https://nixos.org/), you can just type:
@@ -47,7 +47,7 @@ snapshot: lts-YOUR.VERSION
## Install and run
-Once stack is installed, we can install `kycheck` with the command:
+Once stack is installed, we can install `robocop` with the command:
```
$ stack install --local-bin-path DESTINATION_FOLDER
@@ -56,26 +56,26 @@ $ stack install --local-bin-path DESTINATION_FOLDER
If you do not specify a path, the binary will be placed in `~/.local/bin` by default. This means you can run it from there or copy it to the desired location afterwards as well.
```
-$ ~/.local/bin/kycheck --help
+$ ~/.local/bin/robocop --help
```
-You can either provide all the parameters on the command line, or use a configuration file (in [Dhall](https://dhall-lang.org/). There is an example configuration file called `kycheck.conf` available, with reasonably sane defaults. You can specify your own using the flag `--config`.
+You can either provide all the parameters on the command line, or use a configuration file (in [Dhall](https://dhall-lang.org/). There is an example configuration file called `robocop.conf` available, with reasonably sane defaults. You can specify your own using the flag `--config`.
Start the application (we recommend using the more verbose option (using `--info`) until you've gained some experience with the tool), and wait until the data is loaded and the application indicates it is ready to receive your input. After that, you can paste in data about people and organisations you want to check against. Use jsonlines, one line per person or entity. E.g. if you paste:
```{"full_name" : "Maria Consuela", "last_name" : "", "address" : { "country" : "GT", "street_name" : "Unknown", "street_number" : "", "zipcode" : "" }, "birthdate" : "1953-06-23", "nationality" : "GT", "national_id" : "" }```
-kycheck will print something like:
+robocop will print something like:
-```Score {match_quality = 0.85357136, confidence = 0.9311688, expiration = 0, reference = 73508}```
+```{"match_quality":0.85357136, "confidence":0.9311688, "expiration":0, "reference":73508}```
-If there are multiple entries that match, kycheck will print all of them so you can investigate.
+If there are multiple entries that match, robocop will print all of them so you can investigate.
Enter new lines with subject data until you've researched all.
You can also check out legal entities. Using an example organisation from our tests (note that this is an example entity that is not on the sanction list, so we need to provide our own alternative 'sanction list'):
-```$ .local/bin/kycheck --config kycheck.example.conf --input test/data/target_1.xml```
+```$ .local/bin/robocop --config robocop.example.conf --input test/data/target_1.xml```
The input:
@@ -98,4 +98,3 @@ $ stack test
## Updating
Update the repository, and repeat the above steps.
-
diff --git a/app/Main.hs b/app/Main.hs
@@ -14,34 +14,38 @@ import qualified Data.Text as T
import Data.Text.Lazy as TL
import Data.Text.Lazy.Encoding (encodeUtf8)
-import KYCheck.Check
-import KYCheck.Config
-import KYCheck.Error
-import KYCheck.GLS.Type
-import KYCheck.SSL
-import KYCheck.SSL.XML.Type
-import KYCheck.Type
+import Robocop.Check
+import Robocop.Config
+import Robocop.Error
+import Robocop.GLS.Type
+import Robocop.SSL
+import Robocop.SSL.XML.Type
+import Robocop.Type
import Options.Applicative (execParser)
import System.Directory
import System.FilePath
+import System.IO
-import Toml (decodeFile)
+import Toml (decodeFile)
readJSON :: Config -> Targets -> IO ()
readJSON config sanction_list = do
- when (verbosity config >= Info) $ putStrLn "Sanction list loaded. Ready for your input.\n(Paste subject data into the terminal, use JSONlines format)\nType 'quit' to exit."
- line <- getLine
- if line == "quit"
- then print "Thank you for using KYCheck."
- else do case (eitherDecode . encodeUtf8 . TL.pack) line of
- Left err -> print $ "Could not decode JSON (" ++ show err ++ "), please try again"
- Right entry -> case entry of
+ when (verbosity config >= Info) $ hPutStrLn stderr "Sanction list loaded. Ready for your input.\n(Paste subject data into the terminal. Use JSONlines format.)\nType 'CTRL-D' to exit."
+ eof <- isEOF
+ if eof
+ then hPutStrLn stderr "Thank you for using Robocop."
+ else do
+ line <- getLine
+ case (eitherDecode . encodeUtf8 . TL.pack) line of
+ Left err -> hPutStrLn stderr $ "Failed to decode JSON (" ++ show err ++ ")"
+ Right entry -> do
+ case entry of
NP person -> mapM_ print $ checkPersons config (individuals sanction_list) person
LE entity -> mapM_ print $ checkEntity config (entities sanction_list) entity
- readJSON config sanction_list
+ readJSON config sanction_list
main :: IO ()
main = do
@@ -53,7 +57,7 @@ main = do
Nothing -> return ()
Just Silent -> return ()
Just _ -> do curr_dir <- getCurrentDirectory
- putStrLn $ "Searching for '" ++ config_fp ++ "' in " ++ curr_dir
+ hPutStrLn stderr $ "Searching for '" ++ config_fp ++ "' in " ++ curr_dir
toml <- decodeFile configCodec config_fp
@@ -66,17 +70,17 @@ main = do
case valid_config of
False -> return ()
True -> do start <- getCurrentTime
- when (v > Silent) $ print $ "Starting at: " ++ show start
+ when (v > Silent) $ hPutStrLn stderr $ "Starting at " ++ show start
sanction_list <- try $ parseSwissSanctionsList (ssl_location config) :: IO (Either SomeException SwissSanctionsList)
case sanction_list of
Left err -> do curr_dir <- getCurrentDirectory
- _ <- handleError v $ Left $ KYCheck_InvalidXML (T.pack $ curr_dir </> ssl_location config) (show err)
+ _ <- handleError v $ Left $ Robocop_InvalidXML (T.pack $ curr_dir </> ssl_location config) (show err)
return ()
Right xml -> do let tgts = xmlToSSL xml
case start_date tgts of
- Just age -> print $ "Seconds since epoch: " ++ (show (floor $ diffUTCTime start (UTCTime age 0) :: Int))
- Nothing -> print $ "Could not find age of sanction_list"
+ Just age -> hPutStrLn stderr $ "Seconds since epoch: " ++ (show (floor $ diffUTCTime start (UTCTime age 0) :: Int))
+ Nothing -> hPutStrLn stderr $ "Could not find age of sanction list"
readJSON config tgts
diff --git a/debian/changelog b/debian/changelog
@@ -0,0 +1,5 @@
+robocop (0.0.0-1) unstable; urgency=medium
+
+ * Initial release.
+
+ -- Christian Grothoff <grothoff@gnu.org> Thu, 29 May 2025 16:33:33 +0200
diff --git a/debian/control b/debian/control
@@ -0,0 +1,23 @@
+Source: robocop
+Section: net
+Priority: optional
+Maintainer: Christian Grothoff <grothoff@gnu.org>
+Rules-Requires-Root: no
+Build-Depends:
+ debhelper-compat (= 13),
+ ghc,
+ haskell-stack,
+ debhelper,
+ g++-14
+Standards-Version: 4.7.2
+Homepage: https://taler.net/
+#Vcs-Browser: https://salsa.debian.org/debian/taler-exchange-sanctioncheck
+#Vcs-Git: https://salsa.debian.org/debian/taler-exchange-sanctioncheck.git
+
+Package: robocop
+Architecture: any
+Depends:
+ ${misc:Depends},
+ ${shlibs:Depends},
+Description: Tool to check KYC records against sanction lists in GNU Taler.
+ The current implementation should primarily work with the Swiss list.
diff --git a/debian/copyright b/debian/copyright
@@ -0,0 +1,673 @@
+Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
+Source: https://git.gnunet.org/robocop.git/
+Upstream-Name: robocop
+Upstream-Contact: <robocop@taler.net>
+
+Files:
+ *
+Copyright:
+ 2024-2025 Vint Leenars
+Copyright:
+ 2025 Vint Leenars
+License: AGPL-3+
+ GNU AFFERO GENERAL PUBLIC LICENSE
+ Version 3, 19 November 2007
+ .
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+ .
+ Preamble
+ .
+ The GNU Affero General Public License is a free, copyleft license for
+ software and other kinds of works, specifically designed to ensure
+ cooperation with the community in the case of network server software.
+ .
+ The licenses for most software and other practical works are designed
+ to take away your freedom to share and change the works. By contrast,
+ our General Public Licenses are intended to guarantee your freedom to
+ share and change all versions of a program--to make sure it remains free
+ software for all its users.
+ .
+ When we speak of free software, we are referring to freedom, not
+ price. Our General Public Licenses are designed to make sure that you
+ have the freedom to distribute copies of free software (and charge for
+ them if you wish), that you receive source code or can get it if you
+ want it, that you can change the software or use pieces of it in new
+ free programs, and that you know you can do these things.
+ .
+ Developers that use our General Public Licenses protect your rights
+ with two steps: (1) assert copyright on the software, and (2) offer
+ you this License which gives you legal permission to copy, distribute
+ and/or modify the software.
+ .
+ A secondary benefit of defending all users' freedom is that
+ improvements made in alternate versions of the program, if they
+ receive widespread use, become available for other developers to
+ incorporate. Many developers of free software are heartened and
+ encouraged by the resulting cooperation. However, in the case of
+ software used on network servers, this result may fail to come about.
+ The GNU General Public License permits making a modified version and
+ letting the public access it on a server without ever releasing its
+ source code to the public.
+ .
+ The GNU Affero General Public License is designed specifically to
+ ensure that, in such cases, the modified source code becomes available
+ to the community. It requires the operator of a network server to
+ provide the source code of the modified version running there to the
+ users of that server. Therefore, public use of a modified version, on
+ a publicly accessible server, gives the public access to the source
+ code of the modified version.
+ .
+ An older license, called the Affero General Public License and
+ published by Affero, was designed to accomplish similar goals. This is
+ a different license, not a version of the Affero GPL, but Affero has
+ released a new version of the Affero GPL which permits relicensing under
+ this license.
+ .
+ The precise terms and conditions for copying, distribution and
+ modification follow.
+ .
+ TERMS AND CONDITIONS
+ .
+ 0. Definitions.
+ .
+ "This License" refers to version 3 of the GNU Affero General Public License.
+ .
+ "Copyright" also means copyright-like laws that apply to other kinds of
+ works, such as semiconductor masks.
+ .
+ "The Program" refers to any copyrightable work licensed under this
+ License. Each licensee is addressed as "you". "Licensees" and
+ "recipients" may be individuals or organizations.
+ .
+ To "modify" a work means to copy from or adapt all or part of the work
+ in a fashion requiring copyright permission, other than the making of an
+ exact copy. The resulting work is called a "modified version" of the
+ earlier work or a work "based on" the earlier work.
+ .
+ A "covered work" means either the unmodified Program or a work based
+ on the Program.
+ .
+ To "propagate" a work means to do anything with it that, without
+ permission, would make you directly or secondarily liable for
+ infringement under applicable copyright law, except executing it on a
+ computer or modifying a private copy. Propagation includes copying,
+ distribution (with or without modification), making available to the
+ public, and in some countries other activities as well.
+ .
+ To "convey" a work means any kind of propagation that enables other
+ parties to make or receive copies. Mere interaction with a user through
+ a computer network, with no transfer of a copy, is not conveying.
+ .
+ An interactive user interface displays "Appropriate Legal Notices"
+ to the extent that it includes a convenient and prominently visible
+ feature that (1) displays an appropriate copyright notice, and (2)
+ tells the user that there is no warranty for the work (except to the
+ extent that warranties are provided), that licensees may convey the
+ work under this License, and how to view a copy of this License. If
+ the interface presents a list of user commands or options, such as a
+ menu, a prominent item in the list meets this criterion.
+ .
+ 1. Source Code.
+ .
+ The "source code" for a work means the preferred form of the work
+ for making modifications to it. "Object code" means any non-source
+ form of a work.
+ .
+ A "Standard Interface" means an interface that either is an official
+ standard defined by a recognized standards body, or, in the case of
+ interfaces specified for a particular programming language, one that
+ is widely used among developers working in that language.
+ .
+ The "System Libraries" of an executable work include anything, other
+ than the work as a whole, that (a) is included in the normal form of
+ packaging a Major Component, but which is not part of that Major
+ Component, and (b) serves only to enable use of the work with that
+ Major Component, or to implement a Standard Interface for which an
+ implementation is available to the public in source code form. A
+ "Major Component", in this context, means a major essential component
+ (kernel, window system, and so on) of the specific operating system
+ (if any) on which the executable work runs, or a compiler used to
+ produce the work, or an object code interpreter used to run it.
+ .
+ The "Corresponding Source" for a work in object code form means all
+ the source code needed to generate, install, and (for an executable
+ work) run the object code and to modify the work, including scripts to
+ control those activities. However, it does not include the work's
+ System Libraries, or general-purpose tools or generally available free
+ programs which are used unmodified in performing those activities but
+ which are not part of the work. For example, Corresponding Source
+ includes interface definition files associated with source files for
+ the work, and the source code for shared libraries and dynamically
+ linked subprograms that the work is specifically designed to require,
+ such as by intimate data communication or control flow between those
+ subprograms and other parts of the work.
+ .
+ The Corresponding Source need not include anything that users
+ can regenerate automatically from other parts of the Corresponding
+ Source.
+ .
+ The Corresponding Source for a work in source code form is that
+ same work.
+ .
+ 2. Basic Permissions.
+ .
+ All rights granted under this License are granted for the term of
+ copyright on the Program, and are irrevocable provided the stated
+ conditions are met. This License explicitly affirms your unlimited
+ permission to run the unmodified Program. The output from running a
+ covered work is covered by this License only if the output, given its
+ content, constitutes a covered work. This License acknowledges your
+ rights of fair use or other equivalent, as provided by copyright law.
+ .
+ You may make, run and propagate covered works that you do not
+ convey, without conditions so long as your license otherwise remains
+ in force. You may convey covered works to others for the sole purpose
+ of having them make modifications exclusively for you, or provide you
+ with facilities for running those works, provided that you comply with
+ the terms of this License in conveying all material for which you do
+ not control copyright. Those thus making or running the covered works
+ for you must do so exclusively on your behalf, under your direction
+ and control, on terms that prohibit them from making any copies of
+ your copyrighted material outside their relationship with you.
+ .
+ Conveying under any other circumstances is permitted solely under
+ the conditions stated below. Sublicensing is not allowed; section 10
+ makes it unnecessary.
+ .
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+ .
+ No covered work shall be deemed part of an effective technological
+ measure under any applicable law fulfilling obligations under article
+ 11 of the WIPO copyright treaty adopted on 20 December 1996, or
+ similar laws prohibiting or restricting circumvention of such
+ measures.
+ .
+ When you convey a covered work, you waive any legal power to forbid
+ circumvention of technological measures to the extent such circumvention
+ is effected by exercising rights under this License with respect to
+ the covered work, and you disclaim any intention to limit operation or
+ modification of the work as a means of enforcing, against the work's
+ users, your or third parties' legal rights to forbid circumvention of
+ technological measures.
+ .
+ 4. Conveying Verbatim Copies.
+ .
+ You may convey verbatim copies of the Program's source code as you
+ receive it, in any medium, provided that you conspicuously and
+ appropriately publish on each copy an appropriate copyright notice;
+ keep intact all notices stating that this License and any
+ non-permissive terms added in accord with section 7 apply to the code;
+ keep intact all notices of the absence of any warranty; and give all
+ recipients a copy of this License along with the Program.
+ .
+ You may charge any price or no price for each copy that you convey,
+ and you may offer support or warranty protection for a fee.
+ .
+ 5. Conveying Modified Source Versions.
+ .
+ You may convey a work based on the Program, or the modifications to
+ produce it from the Program, in the form of source code under the
+ terms of section 4, provided that you also meet all of these conditions:
+ .
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+ .
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+ .
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+ .
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+ .
+ A compilation of a covered work with other separate and independent
+ works, which are not by their nature extensions of the covered work,
+ and which are not combined with it such as to form a larger program,
+ in or on a volume of a storage or distribution medium, is called an
+ "aggregate" if the compilation and its resulting copyright are not
+ used to limit the access or legal rights of the compilation's users
+ beyond what the individual works permit. Inclusion of a covered work
+ in an aggregate does not cause this License to apply to the other
+ parts of the aggregate.
+ .
+ 6. Conveying Non-Source Forms.
+ .
+ You may convey a covered work in object code form under the terms
+ of sections 4 and 5, provided that you also convey the
+ machine-readable Corresponding Source under the terms of this License,
+ in one of these ways:
+ .
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+ .
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+ .
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+ .
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+ .
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+ .
+ A separable portion of the object code, whose source code is excluded
+ from the Corresponding Source as a System Library, need not be
+ included in conveying the object code work.
+ .
+ A "User Product" is either (1) a "consumer product", which means any
+ tangible personal property which is normally used for personal, family,
+ or household purposes, or (2) anything designed or sold for incorporation
+ into a dwelling. In determining whether a product is a consumer product,
+ doubtful cases shall be resolved in favor of coverage. For a particular
+ product received by a particular user, "normally used" refers to a
+ typical or common use of that class of product, regardless of the status
+ of the particular user or of the way in which the particular user
+ actually uses, or expects or is expected to use, the product. A product
+ is a consumer product regardless of whether the product has substantial
+ commercial, industrial or non-consumer uses, unless such uses represent
+ the only significant mode of use of the product.
+ .
+ "Installation Information" for a User Product means any methods,
+ procedures, authorization keys, or other information required to install
+ and execute modified versions of a covered work in that User Product from
+ a modified version of its Corresponding Source. The information must
+ suffice to ensure that the continued functioning of the modified object
+ code is in no case prevented or interfered with solely because
+ modification has been made.
+ .
+ If you convey an object code work under this section in, or with, or
+ specifically for use in, a User Product, and the conveying occurs as
+ part of a transaction in which the right of possession and use of the
+ User Product is transferred to the recipient in perpetuity or for a
+ fixed term (regardless of how the transaction is characterized), the
+ Corresponding Source conveyed under this section must be accompanied
+ by the Installation Information. But this requirement does not apply
+ if neither you nor any third party retains the ability to install
+ modified object code on the User Product (for example, the work has
+ been installed in ROM).
+ .
+ The requirement to provide Installation Information does not include a
+ requirement to continue to provide support service, warranty, or updates
+ for a work that has been modified or installed by the recipient, or for
+ the User Product in which it has been modified or installed. Access to a
+ network may be denied when the modification itself materially and
+ adversely affects the operation of the network or violates the rules and
+ protocols for communication across the network.
+ .
+ Corresponding Source conveyed, and Installation Information provided,
+ in accord with this section must be in a format that is publicly
+ documented (and with an implementation available to the public in
+ source code form), and must require no special password or key for
+ unpacking, reading or copying.
+ .
+ 7. Additional Terms.
+ .
+ "Additional permissions" are terms that supplement the terms of this
+ License by making exceptions from one or more of its conditions.
+ Additional permissions that are applicable to the entire Program shall
+ be treated as though they were included in this License, to the extent
+ that they are valid under applicable law. If additional permissions
+ apply only to part of the Program, that part may be used separately
+ under those permissions, but the entire Program remains governed by
+ this License without regard to the additional permissions.
+ .
+ When you convey a copy of a covered work, you may at your option
+ remove any additional permissions from that copy, or from any part of
+ it. (Additional permissions may be written to require their own
+ removal in certain cases when you modify the work.) You may place
+ additional permissions on material, added by you to a covered work,
+ for which you have or can give appropriate copyright permission.
+ .
+ Notwithstanding any other provision of this License, for material you
+ add to a covered work, you may (if authorized by the copyright holders of
+ that material) supplement the terms of this License with terms:
+ .
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+ .
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+ .
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+ .
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+ .
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+ .
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+ .
+ All other non-permissive additional terms are considered "further
+ restrictions" within the meaning of section 10. If the Program as you
+ received it, or any part of it, contains a notice stating that it is
+ governed by this License along with a term that is a further
+ restriction, you may remove that term. If a license document contains
+ a further restriction but permits relicensing or conveying under this
+ License, you may add to a covered work material governed by the terms
+ of that license document, provided that the further restriction does
+ not survive such relicensing or conveying.
+ .
+ If you add terms to a covered work in accord with this section, you
+ must place, in the relevant source files, a statement of the
+ additional terms that apply to those files, or a notice indicating
+ where to find the applicable terms.
+ .
+ Additional terms, permissive or non-permissive, may be stated in the
+ form of a separately written license, or stated as exceptions;
+ the above requirements apply either way.
+ .
+ 8. Termination.
+ .
+ You may not propagate or modify a covered work except as expressly
+ provided under this License. Any attempt otherwise to propagate or
+ modify it is void, and will automatically terminate your rights under
+ this License (including any patent licenses granted under the third
+ paragraph of section 11).
+ .
+ However, if you cease all violation of this License, then your
+ license from a particular copyright holder is reinstated (a)
+ provisionally, unless and until the copyright holder explicitly and
+ finally terminates your license, and (b) permanently, if the copyright
+ holder fails to notify you of the violation by some reasonable means
+ prior to 60 days after the cessation.
+ .
+ Moreover, your license from a particular copyright holder is
+ reinstated permanently if the copyright holder notifies you of the
+ violation by some reasonable means, this is the first time you have
+ received notice of violation of this License (for any work) from that
+ copyright holder, and you cure the violation prior to 30 days after
+ your receipt of the notice.
+ .
+ Termination of your rights under this section does not terminate the
+ licenses of parties who have received copies or rights from you under
+ this License. If your rights have been terminated and not permanently
+ reinstated, you do not qualify to receive new licenses for the same
+ material under section 10.
+ .
+ 9. Acceptance Not Required for Having Copies.
+ .
+ You are not required to accept this License in order to receive or
+ run a copy of the Program. Ancillary propagation of a covered work
+ occurring solely as a consequence of using peer-to-peer transmission
+ to receive a copy likewise does not require acceptance. However,
+ nothing other than this License grants you permission to propagate or
+ modify any covered work. These actions infringe copyright if you do
+ not accept this License. Therefore, by modifying or propagating a
+ covered work, you indicate your acceptance of this License to do so.
+ .
+ 10. Automatic Licensing of Downstream Recipients.
+ .
+ Each time you convey a covered work, the recipient automatically
+ receives a license from the original licensors, to run, modify and
+ propagate that work, subject to this License. You are not responsible
+ for enforcing compliance by third parties with this License.
+ .
+ An "entity transaction" is a transaction transferring control of an
+ organization, or substantially all assets of one, or subdividing an
+ organization, or merging organizations. If propagation of a covered
+ work results from an entity transaction, each party to that
+ transaction who receives a copy of the work also receives whatever
+ licenses to the work the party's predecessor in interest had or could
+ give under the previous paragraph, plus a right to possession of the
+ Corresponding Source of the work from the predecessor in interest, if
+ the predecessor has it or can get it with reasonable efforts.
+ .
+ You may not impose any further restrictions on the exercise of the
+ rights granted or affirmed under this License. For example, you may
+ not impose a license fee, royalty, or other charge for exercise of
+ rights granted under this License, and you may not initiate litigation
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
+ any patent claim is infringed by making, using, selling, offering for
+ sale, or importing the Program or any portion of it.
+ .
+ 11. Patents.
+ .
+ A "contributor" is a copyright holder who authorizes use under this
+ License of the Program or a work on which the Program is based. The
+ work thus licensed is called the contributor's "contributor version".
+ .
+ A contributor's "essential patent claims" are all patent claims
+ owned or controlled by the contributor, whether already acquired or
+ hereafter acquired, that would be infringed by some manner, permitted
+ by this License, of making, using, or selling its contributor version,
+ but do not include claims that would be infringed only as a
+ consequence of further modification of the contributor version. For
+ purposes of this definition, "control" includes the right to grant
+ patent sublicenses in a manner consistent with the requirements of
+ this License.
+ .
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+ patent license under the contributor's essential patent claims, to
+ make, use, sell, offer for sale, import and otherwise run, modify and
+ propagate the contents of its contributor version.
+ .
+ In the following three paragraphs, a "patent license" is any express
+ agreement or commitment, however denominated, not to enforce a patent
+ (such as an express permission to practice a patent or covenant not to
+ sue for patent infringement). To "grant" such a patent license to a
+ party means to make such an agreement or commitment not to enforce a
+ patent against the party.
+ .
+ If you convey a covered work, knowingly relying on a patent license,
+ and the Corresponding Source of the work is not available for anyone
+ to copy, free of charge and under the terms of this License, through a
+ publicly available network server or other readily accessible means,
+ then you must either (1) cause the Corresponding Source to be so
+ available, or (2) arrange to deprive yourself of the benefit of the
+ patent license for this particular work, or (3) arrange, in a manner
+ consistent with the requirements of this License, to extend the patent
+ license to downstream recipients. "Knowingly relying" means you have
+ actual knowledge that, but for the patent license, your conveying the
+ covered work in a country, or your recipient's use of the covered work
+ in a country, would infringe one or more identifiable patents in that
+ country that you have reason to believe are valid.
+ .
+ If, pursuant to or in connection with a single transaction or
+ arrangement, you convey, or propagate by procuring conveyance of, a
+ covered work, and grant a patent license to some of the parties
+ receiving the covered work authorizing them to use, propagate, modify
+ or convey a specific copy of the covered work, then the patent license
+ you grant is automatically extended to all recipients of the covered
+ work and works based on it.
+ .
+ A patent license is "discriminatory" if it does not include within
+ the scope of its coverage, prohibits the exercise of, or is
+ conditioned on the non-exercise of one or more of the rights that are
+ specifically granted under this License. You may not convey a covered
+ work if you are a party to an arrangement with a third party that is
+ in the business of distributing software, under which you make payment
+ to the third party based on the extent of your activity of conveying
+ the work, and under which the third party grants, to any of the
+ parties who would receive the covered work from you, a discriminatory
+ patent license (a) in connection with copies of the covered work
+ conveyed by you (or copies made from those copies), or (b) primarily
+ for and in connection with specific products or compilations that
+ contain the covered work, unless you entered into that arrangement,
+ or that patent license was granted, prior to 28 March 2007.
+ .
+ Nothing in this License shall be construed as excluding or limiting
+ any implied license or other defenses to infringement that may
+ otherwise be available to you under applicable patent law.
+ .
+ 12. No Surrender of Others' Freedom.
+ .
+ If conditions are imposed on you (whether by court order, agreement or
+ otherwise) that contradict the conditions of this License, they do not
+ excuse you from the conditions of this License. If you cannot convey a
+ covered work so as to satisfy simultaneously your obligations under this
+ License and any other pertinent obligations, then as a consequence you may
+ not convey it at all. For example, if you agree to terms that obligate you
+ to collect a royalty for further conveying from those to whom you convey
+ the Program, the only way you could satisfy both those terms and this
+ License would be to refrain entirely from conveying the Program.
+ .
+ 13. Remote Network Interaction; Use with the GNU General Public License.
+ .
+ Notwithstanding any other provision of this License, if you modify the
+ Program, your modified version must prominently offer all users
+ interacting with it remotely through a computer network (if your version
+ supports such interaction) an opportunity to receive the Corresponding
+ Source of your version by providing access to the Corresponding Source
+ from a network server at no charge, through some standard or customary
+ means of facilitating copying of software. This Corresponding Source
+ shall include the Corresponding Source for any work covered by version 3
+ of the GNU General Public License that is incorporated pursuant to the
+ following paragraph.
+ .
+ Notwithstanding any other provision of this License, you have
+ permission to link or combine any covered work with a work licensed
+ under version 3 of the GNU General Public License into a single
+ combined work, and to convey the resulting work. The terms of this
+ License will continue to apply to the part which is the covered work,
+ but the work with which it is combined will remain governed by version
+ 3 of the GNU General Public License.
+ .
+ 14. Revised Versions of this License.
+ .
+ The Free Software Foundation may publish revised and/or new versions of
+ the GNU Affero General Public License from time to time. Such new versions
+ will be similar in spirit to the present version, but may differ in detail to
+ address new problems or concerns.
+ .
+ Each version is given a distinguishing version number. If the
+ Program specifies that a certain numbered version of the GNU Affero General
+ Public License "or any later version" applies to it, you have the
+ option of following the terms and conditions either of that numbered
+ version or of any later version published by the Free Software
+ Foundation. If the Program does not specify a version number of the
+ GNU Affero General Public License, you may choose any version ever published
+ by the Free Software Foundation.
+ .
+ If the Program specifies that a proxy can decide which future
+ versions of the GNU Affero General Public License can be used, that proxy's
+ public statement of acceptance of a version permanently authorizes you
+ to choose that version for the Program.
+ .
+ Later license versions may give you additional or different
+ permissions. However, no additional obligations are imposed on any
+ author or copyright holder as a result of your choosing to follow a
+ later version.
+ .
+ 15. Disclaimer of Warranty.
+ .
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+ APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+ OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+ IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+ .
+ 16. Limitation of Liability.
+ .
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+ THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+ GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+ DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+ EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+ SUCH DAMAGES.
+ .
+ 17. Interpretation of Sections 15 and 16.
+ .
+ If the disclaimer of warranty and limitation of liability provided
+ above cannot be given local legal effect according to their terms,
+ reviewing courts shall apply local law that most closely approximates
+ an absolute waiver of all civil liability in connection with the
+ Program, unless a warranty or assumption of liability accompanies a
+ copy of the Program in return for a fee.
+ .
+ END OF TERMS AND CONDITIONS
+ .
+ How to Apply These Terms to Your New Programs
+ .
+ If you develop a new program, and you want it to be of the greatest
+ possible use to the public, the best way to achieve this is to make it
+ free software which everyone can redistribute and change under these terms.
+ .
+ To do so, attach the following notices to the program. It is safest
+ to attach them to the start of each source file to most effectively
+ state the exclusion of warranty; and each file should have at least
+ the "copyright" line and a pointer to where the full notice is found.
+ .
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+ .
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero General Public License as published by
+ the Free Software Foundation, either version 3 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 Affero General Public License for more details.
+ .
+ You should have received a copy of the GNU Affero General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+ .
+ Also add information on how to contact you by electronic and paper mail.
+ .
+ If your software can interact with users remotely through a computer
+ network, you should also make sure that it provides a way for users to
+ get its source. For example, if your program is a web application, its
+ interface could display a "Source" link that leads users to an archive
+ of the code. There are many ways you could offer source, and different
+ solutions will be better for different programs; see section 13 for the
+ specific requirements.
+ .
+ You should also get your employer (if you work as a programmer) or school,
+ if any, to sign a "copyright disclaimer" for the program, if necessary.
+ For more information on this, and how to apply and follow the GNU AGPL, see
+ <http://www.gnu.org/licenses/>.
diff --git a/debian/robocop.install b/debian/robocop.install
@@ -0,0 +1 @@
+usr/bin/*
diff --git a/debian/rules b/debian/rules
@@ -0,0 +1,11 @@
+#!/usr/bin/make -f
+
+%:
+ dh $@
+
+override_dh_auto_build:
+ stack setup
+ stack build --system-ghc --no-install-ghc
+
+override_dh_auto_install:
+ stack install --local-bin-path=debian/tmp/usr/bin --system-ghc --no-install-ghc
diff --git a/debian/source/format b/debian/source/format
@@ -0,0 +1 @@
+3.0 (quilt)
diff --git a/package.yaml b/package.yaml
@@ -3,9 +3,9 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
# SPDX-License-Identifier: EUPL-1.2
-name: kycheck
+name: robocop
version: 0.3
-homepage: https://git.disroot.org/lnrs/kycheck#README.md
+homepage: https://git.taler.net/robocop.git/
author: Vint Leenaars
maintainer: vl.software@leenaa.rs
copyright: 2025 Vint Leenaars and KYCheck contributors
@@ -24,7 +24,7 @@ category: Finance
# To avoid duplicated efforts in documentation and dealing with the
# complications of embedding Haddock markup inside cabal files, it is
# common to point users to the README.md file.
-description: KYCheck is a CTF tool to check sanctions <https://git.disroot.org/lnrs/kycheck>
+description: Robocop is a CTF tool to check sanctions <https://git.disroot.org/lnrs/kycheck>
dependencies:
- aeson
@@ -59,20 +59,20 @@ library:
source-dirs: src
executables:
- kycheck:
+ robocop:
main: Main.hs
- source-dirs: app
- dependencies: kycheck
+ source-dirs: app
+ dependencies: robocop
ghc-options:
- -threaded
- -rtsopts
- -with-rtsopts=-N
tests:
- kycheck-test:
- main: test-kycheck.hs
+ robocop-test:
+ main: test-robocop.hs
source-dirs: test
- dependencies: kycheck
+ dependencies: robocop
ghc-options:
- -threaded
- -rtsopts
diff --git a/kycheck.conf b/robocop.conf
diff --git a/kycheck.example.conf b/robocop.example.conf
diff --git a/src/KYCheck/Check.hs b/src/KYCheck/Check.hs
@@ -1,310 +0,0 @@
--- SPDX-FileCopyrightText: 2025 LNRS
---
--- SPDX-License-Identifier: AGPL-3.0-or-later
--- SPDX-License-Identifier: EUPL-1.2
-
-{-# LANGUAGE OverloadedStrings #-}
-
-module KYCheck.Check
- ( checkAddress
- , checkBirthDate
- , checkCountryCode
- , checkEntity
- , checkID
- , checkNames
- , checkPersons
- , compareFullDate
- , multFloats
- , Score(..)
- ) where
-
-import Data.ISO3166_CountryCodes
-import Data.List (permutations, subsequences)
-import Data.Maybe
-import Data.Map (Map, toList)
-import Data.Ratio
-
-import Data.Text (intercalate, pack, snoc, Text)
-import qualified Data.Text as T
-import Data.Text.Metrics
-
-import Data.Time.Calendar
-import Data.Time.Calendar.OrdinalDate
-
-import KYCheck.Type
-import KYCheck.SSL.Type as SSL
-import KYCheck.GLS.Type as GLS
-
-import Prelude hiding (lines)
-
-data Score = Score
- { match_quality :: Float
- , confidence :: Float
- , expiration :: Int
- , reference :: Int
- } deriving (Show, Eq)
-
-suspicious_dates :: (Int, Int)
-suspicious_dates = (3, 75) -- Difference in years and days that will be marked suspicious (exponential)
-
-type QualityFloat = Quality Float
-
-
-
-checkEntity :: Config -> Map Int Entity -> LegalEntity -> [Score]
-checkEntity config entities' entity = findMatchingEntities config entity $ toList entities'
-
-findMatchingEntities :: Config -> LegalEntity -> [(Int, Entity)] -> [Score]
-findMatchingEntities _ _ [] = []
-findMatchingEntities config entity ((ssid,ent):ents) =
- let
- points = compareEntity config entity ent
- max_points = foldl1 (+) [ if toList (entity_addresses ent) == [] then 0 else weight_address config
- , if toList (entity_names ent) == [] then 0 else weight_name config
- ]
- in
- if points >= threshold_points config || points / max_points >= threshold_confidence config
- then let
- score = Score { match_quality = if points >= perfect_points config then 1 else points / perfect_points config
- , confidence = points / max_points
- , expiration = 0
- , reference = ssid
- }
- in
- score:findMatchingEntities config entity ents
- else findMatchingEntities config entity ents
-
-compareEntity :: Config -> LegalEntity -> Entity -> Float
-compareEntity config legal_entity entity =
- foldl1 (+) [ multFloats (weight_address config) address_score (removeQuality . removeSSID)
- , multFloats (weight_name config) name_score (removeQuality . removeSSID)
- -- TODO: add additional information to score (phone, email, ...)
- -- , multFloats 300 info_score removeSSID
- ]
- where address_score = checkAddress config (entity_addresses entity) (address legal_entity)
- name_score = checkNames config (entity_names entity) (company_name legal_entity)
- -- info_score = ...
-
-
-
-checkPersons :: Config -> Map Int Individual -> NaturalPerson -> [Score]
-checkPersons config individuals' person = checkPersons' config person $ toList individuals'
-
-checkPersons' :: Config -> NaturalPerson -> [(Int, Individual)] -> [Score]
-checkPersons' _ _ [] = []
-checkPersons' config person ((ssid,ind):inds) =
- let
- points = checkPerson config person ind
- max_points = foldl1 (+) [ if toList (addresses ind) == [] then 0 else weight_address config
- , if toList (birth_dates ind) == [] then 0 else weight_date config
- , if toList (ids ind) == [] then 0 else weight_id config
- , if toList (names ind) == [] then 0 else weight_name config
- , if toList (nationalities ind) == [] then 0 else weight_nationality config
- ]
- in
- if points >= threshold_points config || points / max_points >= threshold_confidence config
- then let
- score = Score { match_quality = if points >= perfect_points config then 1 else points / perfect_points config
- , confidence = points / max_points
- , expiration = 0
- , reference = ssid
- }
- in
- score:checkPersons' config person inds
- else checkPersons' config person inds
-
-checkPerson :: Config -> NaturalPerson -> Individual -> Float
-checkPerson config person individual = foldl1 (+) [ address_points
- , multFloats 200 id_score removeSSID
- , multFloats 100 date_score (removeQuality . removeSSID)
- , 50 * nationality_score
- , name_points
- ]
- where address_score = checkAddress config (addresses individual) (residential person)
- id_score = checkID config (ids individual) (national_id person)
- nationality_score = checkCountryCode config (nationalities individual) (nationality person)
- name_score = checkNames config (names individual) (full_name person)
- date_score = if name_points == 0
- then []
- else checkBirthDate config (birth_dates individual) (birthdate person)
- address_points = multFloats 150 address_score (removeQuality . removeSSID)
- name_points = if address_points >= 100
- then 125
- else multFloats 125 name_score (removeQuality . removeSSID)
-
-multFloats :: Float -> [a] -> (a -> Float) -> Float
-multFloats factor list toFloat = factor * foldl (\n x -> max n $ toFloat x) 0 list
-
-
-
-checkBirthDate :: Config -> Map Int (Quality (Year, Maybe DayOfYear)) -> Day' -> [WithSSID QualityFloat]
-checkBirthDate config dates (Day' date) = catMaybes $ map compareDate $ toList dates
- where compareDate (ssid, quality) = let
- ratio = case removeQuality quality of
- (year, Just day_of_year) -> compareFullDate config year day_of_year date
- (year, Nothing) -> compareYear config year date
- in
- if ratio >= threshold_ratio config
- then Just $ WithSSID ssid $ liftQuality (\_ -> ratio) quality
- else Nothing
-
-compareFullDate :: Config -> Year -> DayOfYear -> Day -> Float
-compareFullDate config year day_of_year day = max ratio_text ratio_date
- where day' = fromOrdinalDate year day_of_year
- day_to_text d = pack $ showGregorian d
- threshold = threshold_ratio config
- ratio_text = let
- ratio = ratioToFloat $ damerauLevenshteinNorm (day_to_text day) (day_to_text day')
- in
- if ratio >= threshold then ratio else 0
-
- (year', day_of_year') = toOrdinalDate day
- (sus_years, sus_days) = suspicious_dates
-
- ratio_days = threshold**((fromIntegral $ abs $ day_of_year - day_of_year') / fromIntegral sus_days)
- ratio_years = threshold**((fromIntegral $ abs $ year - year') / fromIntegral sus_years)
- ratio_date = let
- ratio = ratio_days * ratio_years
- in
- if ratio >= threshold then ratio else 0
-
-compareYear :: Config -> Year -> Day -> Float
-compareYear config year day = if ratio >= threshold then ratio else 0
- where (year', _) = toOrdinalDate day
- (sus_years, _) = suspicious_dates
- threshold = threshold_ratio config
- ratio = threshold**((fromIntegral $ abs $ year - year') / fromIntegral sus_years)
-
-
-
-checkNames :: Config -> Map Int (Quality [Text]) -> Text -> [WithSSID QualityFloat]
-checkNames config names' name = catMaybes $ map compareName $ toList names'
- where compareName (ssid, quality) = let
- ratio = ratioToFloat $ compareText name 0 (removeQuality quality)
- in
- if ratio >= threshold_ratio config
- then Just $ WithSSID ssid $ liftQuality (\_ -> ratio) quality
- else Nothing
-
-
-
-checkCountryCode :: Config -> Map Int CountryCode -> CountryCode -> Float
-checkCountryCode _ countries country' = if foldl (\b (_,c) -> c == country' || b) False $ toList countries then 1 else 0
-
-
-checkID :: Config -> Map Int Text -> Text -> [WithSSID Float]
-checkID config ids' id' = catMaybes $ map compareID $ toList ids'
- where compareID (ssid, id'') = let
- ratio = ratioToFloat $ compareText id' 0 [id'']
- in
- if ratio >= (threshold_ratio config + 1) / 2
- then Just $ WithSSID ssid ratio
- else Nothing
-
-
-checkAddress :: Config -> Map Int (Quality SSL.Address) -> GLS.Address -> [WithSSID QualityFloat]
-checkAddress config addresses' address' = catMaybes $ map (compareAddress config address') $ toList addresses'
-
-compareAddress :: Config -> GLS.Address -> (Int, Quality SSL.Address) -> Maybe (WithSSID QualityFloat)
-compareAddress config gls_address (ssid, quality) = if country_score >= 0.75
- then Just $ WithSSID ssid $ liftQuality (\_ -> country_score) quality
- else Nothing
- where ssl_address = removeQuality quality
- total_score = totalFromMaybes [ details_score
- , area_score
- , location_score
- , zip_code_score
- ]
- country_score = case SSL.country ssl_address of
- Just c -> if c == GLS.country gls_address then 0.5 * (total_score + 1) else 0
- Nothing -> total_score
- details_score = case details ssl_address of
- Just det -> let
- possible_numbers = catMaybes [ Just $ street_number gls_address
- , building_number gls_address
- , lines gls_address
- ]
- possible_info = catMaybes [ Just $ street_name gls_address
- , building_name gls_address
- , country_subdivision gls_address
- , town_district gls_address
- , town_location gls_address
- , Just $ zipcode gls_address
- ]
- possible_details = possible_numbers ++ possible_info
- perms = permutateText possible_details
- clean_details = cleanText det
- ratio = ratioToFloat $ compareTexts clean_details 0 perms
- perfect_matches = foldl (\c i -> if foldl (\b d -> b || i `T.isInfixOf` d) False clean_details then c + 1 else c) 0 possible_info
- in
- Just $ if ratio >= threshold_ratio config
- then ratio
- else if perfect_matches >= 3 then perfect_matches * 0.2 else if perfect_matches > 1 then 0.5 else 0
- Nothing -> Nothing
- area_score = case area ssl_address of
- Just areas -> let
- perms = permutateText $ catMaybes [ town_location gls_address
- , town_district gls_address
- , country_subdivision gls_address
- ]
- ratio = ratioToFloat $ compareTexts areas 0 perms
- in
- if ratio >= threshold_ratio config then Just ratio else Nothing
- Nothing -> Nothing
- location_score = case location ssl_address of
- Just lcs -> let
- perms = permutateText $ catMaybes [ town_location gls_address
- , town_district gls_address
- , country_subdivision gls_address
- ]
- ratio = ratioToFloat $ compareTexts lcs 0 perms
- in
- if ratio >= threshold_ratio config then Just ratio else Nothing
- Nothing -> Nothing
- zip_code_score = case zip_code ssl_address of
- Just zc -> let
- ratio = ratioToFloat $ compareText zc 0 [zipcode gls_address]
- in
- if ratio >= threshold_ratio config then Just ratio else Nothing
- Nothing -> Nothing
-
-
-cleanText :: [Text] -> [Text]
-cleanText text = map (T.foldl (\new_text char -> if char `elem` chars_to_rm
- then new_text
- else snoc new_text char
- ) start_text) text
- where chars_to_rm = ".,-" :: String
- start_text = "" :: Text
-
-permutateText :: [Text] -> [Text]
-permutateText elems = map (intercalate " ") $ concatMap permutations $ subsequences elems
-
-totalFromMaybes :: [Maybe Float] -> Float
-totalFromMaybes floats = let
- list = catMaybes floats
- elems = length list
- total = foldl (+) 0 list
- in
- if elems == 0 then 0 else total / fromIntegral elems
-
-ratioToFloat :: Ratio Int -> Float
-ratioToFloat r = (fromIntegral . numerator) r / (fromIntegral . denominator) r
-
-compareTexts :: [Text] -> Ratio Int -> [Text] -> Ratio Int
-compareTexts _ ratio [] = ratio
-compareTexts texts ratio (t:ts) = let
- new_ratio = compareText t ratio texts
- in
- if new_ratio > ratio
- then compareTexts texts new_ratio ts
- else compareTexts texts ratio ts
-
-compareText :: Text -> Ratio Int -> [Text] -> Ratio Int
-compareText _ ratio [] = ratio
-compareText text ratio (t:ts) = let
- new_ratio = damerauLevenshteinNorm text t
- in
- if new_ratio > ratio
- then compareText text new_ratio ts
- else compareText text ratio ts
diff --git a/src/KYCheck/Config.hs b/src/KYCheck/Config.hs
@@ -1,228 +0,0 @@
--- SPDX-FileCopyrightText: 2025 LNRS
---
--- SPDX-License-Identifier: AGPL-3.0-or-later
--- SPDX-License-Identifier: EUPL-1.2
-
-{-# LANGUAGE DeriveGeneric #-}
-{-# LANGUAGE OverloadedStrings #-}
-{-# LANGUAGE LambdaCase #-}
-
-module KYCheck.Config
- ( inputToConfig
- , checkConfig
- , configCodec
- , opts
- ) where
-
-import KYCheck.Error
-import KYCheck.Type
-
-import Control.Monad
-
-import qualified Data.Text as T
-
-import Options.Applicative
-
-import System.Directory
-import System.FilePath
-
-import Toml as Toml hiding (bool)
-
-inputToConfig :: Config -> CommandLine -> Config
-inputToConfig toml cl =
- Config { verbosity = case cl_verbosity cl of Just v -> v; Nothing -> verbosity toml
- , ssl_location = case cl_ssl_location cl of Just l -> l; Nothing -> ssl_location toml
- , threshold_ratio = case cl_threshold_ratio cl of Just p -> p; Nothing -> threshold_ratio toml
- , threshold_points = case cl_threshold_points cl of Just p -> p; Nothing -> threshold_points toml
- , threshold_confidence = case cl_threshold_confidence cl of Just p -> p; Nothing -> threshold_confidence toml
- , perfect_points = case cl_perfect_points cl of Just p -> p; Nothing -> perfect_points toml
- , weight_address = case cl_weight_address cl of Just p -> p; Nothing -> weight_address toml
- , weight_date = case cl_weight_date cl of Just p -> p; Nothing -> weight_date toml
- , weight_id = case cl_weight_id cl of Just p -> p; Nothing -> weight_id toml
- , weight_name = case cl_weight_name cl of Just p -> p; Nothing -> weight_name toml
- , weight_nationality = case cl_weight_nationality cl of Just p -> p; Nothing -> weight_nationality toml
- }
-
-checkConfig :: Config -> IO Bool
-checkConfig config = do
- valid_ssl <- checkSSL config
- valid_points <- checkPoints config
-
- let valid = foldl1 (&&) [ valid_ssl
- , valid_points
- ]
- return valid
-
-checkSSL :: Config -> IO Bool
-checkSSL config = do
- let fp = ssl_location config
- let v = verbosity config
-
- bool <- do exists <- doesFileExist fp
- when (not exists) $ do curr_dir <- getCurrentDirectory
- (handleError v . Left) $ KYCheck_NotFound (T.pack $ curr_dir </> fp) ".xml file containing sanctions"
- -- TODO: implement RelaxNG validation
- return exists
-
- return bool
-
-checkPoints :: Config -> IO Bool
-checkPoints config = do
- let v = verbosity config
-
- bool <- do let total = foldl1 (+) [ weight_address config
- , weight_date config
- , weight_id config
- , weight_name config
- , weight_nationality config
- ]
- threshold = threshold_points config
- when (total < threshold)
- $ do (handleError v . Left)
- $ KYCheck_InvalidDistribution
- $ T.pack ("Total points obtainable (" ++ show total ++ ") lower than threshold (" ++ show threshold ++ ")")
- when (threshold_ratio config < 0 || threshold_ratio config > 1)
- $ do (handleError v . Left) $ KYCheck_InvalidDistribution "Threshold ratio should be between 0 and 1"
- when (threshold_confidence config < 0 || threshold_confidence config > 1)
- $ do (handleError v . Left) $ KYCheck_InvalidDistribution "Threshold confidence should be between 0 and 1"
- when (threshold_points config < 0)
- $ do (handleError v . Left) $ KYCheck_InvalidDistribution "Threshold points should be positive"
- when (perfect_points config < 0)
- $ do (handleError v . Left) $ KYCheck_InvalidDistribution "Perfect points should be positive"
- when (weight_address config < 0)
- $ do (handleError v . Left) $ KYCheck_InvalidDistribution "Address weight should be positive"
- when (weight_date config < 0)
- $ do (handleError v . Left) $ KYCheck_InvalidDistribution "Birthdate weight should be positive"
- when (weight_id config < 0)
- $ do (handleError v . Left) $ KYCheck_InvalidDistribution "Identification document weight should be positive"
- when (weight_name config < 0)
- $ do (handleError v . Left) $ KYCheck_InvalidDistribution "Name weight should be positive"
- when (weight_nationality config < 0)
- $ do (handleError v . Left) $ KYCheck_InvalidDistribution "Nationality weight should be positive"
- return (total >= threshold)
- return bool
-
-
-
--- | Toml config parsing
-configCodec :: TomlCodec Config
-configCodec = Config
- <$> verbosityCodec "verbosity" .= verbosity
- <*> Toml.string "ssl_location" .= ssl_location
- <*> Toml.float "threshold_ratio" .= threshold_ratio
- <*> Toml.float "threshold_points" .= threshold_points
- <*> Toml.float "threshold_confidence" .= threshold_confidence
- <*> Toml.float "perfect_points" .= perfect_points
- <*> Toml.float "weight_address" .= weight_address
- <*> Toml.float "weight_date" .= weight_date
- <*> Toml.float "weight_id" .= weight_id
- <*> Toml.float "weight_name" .= weight_name
- <*> Toml.float "weight_nationality" .= weight_nationality
-
-verbosityCodec :: Key -> TomlCodec Verbosity
-verbosityCodec = textBy showVerbosity parseVerbosity
-
-showVerbosity :: Verbosity -> T.Text
-showVerbosity v = case v of
- Test -> "Test"
- Silent -> "Silent"
- Info -> "Info"
- Errors -> "Errors"
- Debug -> "Debug"
-
-parseVerbosity :: T.Text -> Either T.Text Verbosity
-parseVerbosity txt = case txt of
- "Test" -> Right Test
- "Silent" -> Right Silent
- "Info" -> Right Info
- "Errors" -> Right Errors
- "Debug" -> Right Debug
- other -> Left $ "Invalid verbosity: " <> other
-
-
-
-
--- | Custom commandline flag for verbosity-level Silent: --silent
-verbositySilent :: Parser Verbosity
-verbositySilent = flag' Silent
- ( long "silent"
- <> help "Print nothing to commandline unless an error occurs" )
-
--- | Custom commandline flag for verbosity-level Info: --info
-verbosityInfo :: Parser Verbosity
-verbosityInfo = flag' Info
- ( long "info"
- <> help "Only print information about the process to commandline" )
-
--- | Custom commandline flag for verbosity-level Errors: --errors
-verbosityErrors :: Parser Verbosity
-verbosityErrors = flag' Errors
- ( long "errors"
- <> help "Print all error messages to commandline" )
-
--- | Custom commandline flag for verbosity-level Debug: --debug
-verbosityDebug :: Parser Verbosity
-verbosityDebug = flag' Debug
- ( long "debug"
- <> help "Print all available information to commandline" )
-
--- | Custom commandline parser for Verbosity type
-verbosityParser :: Parser Verbosity
-verbosityParser = verbositySilent <|> verbosityInfo <|> verbosityErrors <|> verbosityDebug
-
--- | Custom commandline parser for CommandLine type
-commandLine :: Parser CommandLine
-commandLine = CommandLine
- <$> optional verbosityParser
- <*> strOption
- ( long "config"
- <> metavar "FILENAME"
- <> help "Location of config file"
- <> value "kycheck.conf" )
- <*> optional ( strOption
- ( long "input"
- <> metavar "FILENAME"
- <> help "Location of Swiss Sanction List" ) )
- <*> optional ( option auto
- ( long "threshold-ratio"
- <> metavar "Float"
- <> help "Ratio between 0-1" ) )
- <*> optional ( option auto
- ( long "threshold-points"
- <> metavar "Integer"
- <> help "Points needed to flag entry as match" ) )
- <*> optional ( option auto
- ( long "threshold-confidence"
- <> metavar "Float"
- <> help "Minimum confidence level between 0-1" ) )
- <*> optional ( option auto
- ( long "perfect-points"
- <> metavar "Integer"
- <> help "Amount of points required to get a 100% confidence result" ) )
- <*> optional ( option auto
- ( long "address-weight"
- <> metavar "Integer"
- <> help "Points given to a 100% address match" ) )
- <*> optional ( option auto
- ( long "date-weight"
- <> metavar "Integer"
- <> help "Points given to a 100% birthdate match" ) )
- <*> optional ( option auto
- ( long "id-weight"
- <> metavar "Integer"
- <> help "Points given to a 100% identification document match" ) )
- <*> optional ( option auto
- ( long "name-weight"
- <> metavar "Integer"
- <> help "Points given to a 100% name match" ) )
- <*> optional ( option auto
- ( long "nationality-weight"
- <> metavar "Integer"
- <> help "Points given to a 100% nationality match" ) )
-
--- | Information about CommandLine parser
-opts :: ParserInfo CommandLine
-opts = info (commandLine <**> helper)
- ( fullDesc
- <> progDesc "Match customers to Swiss Sanction List"
- <> header "KYCheck by LNRS" )
diff --git a/src/KYCheck/Error.hs b/src/KYCheck/Error.hs
@@ -1,88 +0,0 @@
--- SPDX-FileCopyrightText: 2025 LNRS
---
--- SPDX-License-Identifier: AGPL-3.0-or-later
--- SPDX-License-Identifier: EUPL-1.2
-
-{-# LANGUAGE DeriveDataTypeable #-}
-{-# LANGUAGE DeriveGeneric #-}
-{-# LANGUAGE OverloadedStrings #-}
-
-module KYCheck.Error
- ( KYCheck_Error(..)
- , renderError
- , handleError
- , showError
- ) where
-
-import KYCheck.Type
-
-import Control.Exception (Exception, SomeException)
-import Control.Monad (when)
-import Data.Text (Text)
-import Data.Typeable (Typeable)
-import GHC.Generics (Generic)
-import System.Exit (ExitCode (..), exitWith)
-import System.IO hiding (hPutStrLn)
-
-import qualified Data.Text as T (pack)
-import qualified Data.Text.IO as TIO
-
--- | Custom type to express exceptions in DMARC.* that cause errors
-data KYCheck_Error = KYCheck_InvalidDistribution Text
- | KYCheck_InvalidRelaxNG Text
- | KYCheck_InvalidXML Text String
- | KYCheck_NotFound Text Text
- | KYCheck_NotImplemented Text
- | KYCheck_XMLParsingError Text SomeException
- deriving (Show, Typeable, Generic)
-
-instance Exception KYCheck_Error
-
-renderError :: KYCheck_Error -> Text
-renderError e =
- case e of
- KYCheck_InvalidDistribution msg -> "Error: " <> msg
- KYCheck_InvalidRelaxNG fp -> "Error: " <> fp <> " is not a valid RelaxNG-schema"
- KYCheck_InvalidXML fp err' -> "Error: " <> fp <> " is not valid for RelaxNG-schema\n" <> tshow err'
- KYCheck_NotImplemented msg -> "Error: " <> msg <> " has not been implemented yet, please change your configuration file"
- KYCheck_NotFound fp desc -> "Error: could not find " <> fp <> " (" <> desc <> ")"
- KYCheck_XMLParsingError dat err' -> "Error: could not parse " <> dat <> "\n" <> tshow err'
-
-handleError :: Verbosity -> Either KYCheck_Error a -> IO a
-handleError _ (Right r) = return r
-handleError v (Left e) =
- case e of
- _ -> err v exit_code (renderError e)
- where
- exit_code =
- case e of
- KYCheck_InvalidDistribution{} -> 1
- KYCheck_InvalidRelaxNG{} -> 2
- KYCheck_InvalidXML{} -> 3
- KYCheck_NotImplemented{} -> 4
- KYCheck_NotFound{} -> 5
- KYCheck_XMLParsingError{} -> 6
-
--- | Function to show helpfull error/warning message
-showError :: KYCheck_Error -> IO ()
-showError e = hPutStrLn stderr (renderError e)
-
--- | Function to exit program with specific exit code and msg
-err :: Verbosity -> Int -> Text -> IO a
-err v exit_code msg = do
- when (v /= Test) $ hPutStrLn stderr msg
- _ <- exitWith $ ExitFailure exit_code
- return undefined
-
--- | Convert any Showable type to T.Text
-tshow :: Show a => a -> Text
-tshow = T.pack . show
-
--- | Print T.Text nicely to commandline
-hPutStrLnWith :: Newline -> Handle -> Text -> IO ()
-hPutStrLnWith eol h s =
- hSetNewlineMode h (NewlineMode eol eol) >>
- hSetEncoding h utf8 >> TIO.hPutStrLn h s
-
-hPutStrLn :: Handle -> Text -> IO ()
-hPutStrLn = hPutStrLnWith nativeNewline
diff --git a/src/KYCheck/GLS/Type.hs b/src/KYCheck/GLS/Type.hs
@@ -1,136 +0,0 @@
--- SPDX-FileCopyrightText: 2025 LNRS
---
--- SPDX-License-Identifier: AGPL-3.0-or-later
--- SPDX-License-Identifier: EUPL-1.2
-
--- | See https://git.taler.net/gana.git/tree/gnu-taler-form-attributes/registry.rec
-
-{-# LANGUAGE DeriveGeneric #-}
-{-# LANGUAGE OverloadedStrings #-}
-{-# LANGUAGE PatternSynonyms #-}
-{-# LANGUAGE ViewPatterns #-}
-{-# OPTIONS_GHC -Wno-orphans #-}
-
-module KYCheck.GLS.Type
- ( Address(..)
- , Entry(..)
- , LegalEntity(..)
- , NaturalPerson(..)
- , pattern YMD
- ) where
-
-import Control.Applicative ((<|>))
-
-import Data.Aeson (FromJSON(..), ToJSON(..), (.:), (.:?), Value(..))
-import Data.ISO3166_CountryCodes hiding (NP)
-import Data.Text
-
-import GHC.Generics
-
-import KYCheck.Type
-
-data Entry = NP NaturalPerson
- | LE LegalEntity deriving (Show, Generic, Eq)
- -- | F
-
-data NaturalPerson = NaturalPerson
- { full_name :: Text
- , last_name :: Text
- , residential :: Address
--- , phone :: Maybe Text
--- , email :: Maybe Text
- , birthdate :: Day' -- parseTimeM False defaultTimeLocale "%Y-%-m-%-d" YYYY-MM-DD
- , nationality :: CountryCode -- 2-letter ISO country-code
- , national_id :: Text
--- , national_id_copy :: FilePath
--- , company_name :: Maybe Text
--- , registered_office :: Maybe Text
--- , company_id :: Maybe Text
--- , company_id_copy :: Maybe FilePath
- } deriving (Show, Eq, Generic)
-
-data Address = Address
- { country :: CountryCode -- 2-letter ISO country-code
- , street_name :: Text
- , street_number :: Text
- , lines :: Maybe Text -- Additional address information
- , building_name :: Maybe Text
- , building_number :: Maybe Text
- , zipcode :: Text
- , town_location :: Maybe Text
- , town_district :: Maybe Text
- , country_subdivision :: Maybe Text
- } deriving (Show, Eq, Generic)
-
-data LegalEntity = LegalEntity
- { company_name :: Text
- , address :: Address
- , contact_person_name :: Maybe Text
- , phone :: Maybe Text
- , email :: Maybe Text
- , id :: Text
--- , id_copy :: FilePath
- } deriving (Show, Eq, Generic)
-
-instance FromJSON Entry where
- parseJSON e =
- (NP <$> parseJSON e)
- <|> (LE <$> parseJSON e)
-instance FromJSON NaturalPerson where
- parseJSON (Object p) = NaturalPerson
- <$> p .: "full_name"
- <*> p .: "last_name"
- <*> p .: "address"
- <*> p .: "birthdate"
- <*> p .: "nationality"
- <*> p .: "national_id"
- parseJSON _ = fail "Expected a natural person object"
-instance FromJSON Address where
- parseJSON (Object a) = Address
- <$> a .: "country"
- <*> a .: "street_name"
- <*> a .: "street_number"
- <*> a .:? "lines"
- <*> a .:? "building_name"
- <*> a .:? "building_number"
- <*> a .: "zipcode"
- <*> a .:? "town_location"
- <*> a .:? "town_district"
- <*> a .:? "country_subdivision"
- parseJSON _ = fail "Expected an address object"
-instance FromJSON LegalEntity where
- parseJSON (Object e) = LegalEntity
- <$> e .: "company_name"
- <*> e .: "address"
- <*> e .:? "contact_person_name"
- <*> e .:? "phone"
- <*> e .:? "email"
- <*> e .: "id"
- parseJSON _ = fail "Expected a legal entity object"
-instance FromJSON CountryCode where
- parseJSON (String t) = pure (read $ unpack t)
- parseJSON _ = fail "Expected ISO3166 compliant country code"
-
-
-instance ToJSON Entry
-instance ToJSON NaturalPerson
-instance ToJSON Address
-instance ToJSON LegalEntity
-instance ToJSON CountryCode where
- toJSON = toJSON . show
-
--- data Founder = Founder
--- { full_name :: Text
--- , residential_address :: ResidentialAddress
--- , birthdate :: AbsoluteDate
--- , nationality :: CountryCode
--- , authorization_type :: Text
--- , national_id :: Text
--- , national_copy :: FilePath
--- , power_of_attorney :: Maybe Powers
--- , power_of_attorney_other :: Maybe Text
--- } deriving (Show, Eq)
-
-data Powers = CR
- | MANDATE
- | OTHER deriving (Show, Eq)
diff --git a/src/KYCheck/SSL.hs b/src/KYCheck/SSL.hs
@@ -1,14 +0,0 @@
--- SPDX-FileCopyrightText: 2025 LNRS
---
--- SPDX-License-Identifier: AGPL-3.0-or-later
--- SPDX-License-Identifier: EUPL-1.2
-
-module KYCheck.SSL
- ( module KYCheck.SSL.Match
- , module KYCheck.SSL.Type
- , parseSwissSanctionsList
- ) where
-
-import KYCheck.SSL.Match
-import KYCheck.SSL.Type
-import KYCheck.SSL.XML.Parse (parseSwissSanctionsList)
diff --git a/src/KYCheck/SSL/Match.hs b/src/KYCheck/SSL/Match.hs
@@ -1,162 +0,0 @@
--- SPDX-FileCopyrightText: 2025 LNRS
---
--- SPDX-License-Identifier: AGPL-3.0-or-later
--- SPDX-License-Identifier: EUPL-1.2
-
-{-# LANGUAGE OverloadedStrings #-}
-
-module KYCheck.SSL.Match
- ( xmlToSSL
- ) where
-
-import Prelude hiding (lookup)
-
-import Control.Monad (liftM2)
-
-import Data.ISO3166_CountryCodes
-import Data.List (sortOn, permutations, subsequences)
-import Data.Map (insert, Map, lookup, empty)
-import Data.Maybe
-import Data.Time.Format
-import Data.Time.Calendar (fromGregorian)
-import Data.Time.Calendar.OrdinalDate
-
-import qualified Data.Text as T
-
-import KYCheck.Type
-import KYCheck.SSL.Type as SSL
-
-import KYCheck.SSL.XML.Type as XML
-import qualified KYCheck.SSL.XML.Entity.Type as Ent
-import qualified KYCheck.SSL.XML.Individual.Type as Ind
--- import qualified KYC.SSL.XML.Object.Type as Obj
-
-import Text.Read (readMaybe)
-
-xmlToSSL :: SwissSanctionsList -> Targets
-xmlToSSL xml = let
- targets' = map (\(WithSSID _ t) -> target_type t) (targets xml)
- entities' = mapMaybe (\t -> case t of Ent ent -> Just ent; _ -> Nothing) targets'
- individuals' = mapMaybe (\t -> case t of Ind ind -> Just ind; _ -> Nothing) targets'
- -- objects' = mapMaybe (\t -> case t of Obj obj -> Just obj; _ -> Nothing) targets'
- places' = foldl (\ps (WithSSID ssid p) -> insert ssid p ps) empty (XML.places xml)
- in
- Targets { start_date = parseTimeM True defaultTimeLocale "%Y-%-m-%-d" $ T.unpack $ date xml
- , entities = foldl (insertEntity places') empty entities'
- , individuals = foldl (insertIndividual places') empty individuals'
- }
-
-insertEntity :: Map Int XML.Place -> Map Int SSL.Entity -> WithSSID Ent.Entity -> Map Int SSL.Entity
-insertEntity places' map' (WithSSID ssid entity) = insert ssid ssl_entity map'
- where ssl_entity = SSL.Entity { entity_addresses = ssl_addresses
- , entity_dates = ssl_dates
- , entity_names = ssl_names
- , SSL.other_info = ssl_info
- }
- ssl_addresses = case Ent.addresses entity of
- Just addr -> foldl (insertAddress places') empty addr
- Nothing -> empty
- ssl_dates = case Ent.dates entity of
- Just ds -> foldl (insertFuncWithSSID $ liftQuality dateToOrdinal) empty ds
- Nothing -> empty
- ssl_names = foldl (insertFuncWithSSID permutateNames) empty (Ent.names entity)
- ssl_info = case Ent.other_info entity of
- Just info -> foldl insertWithSSID empty info
- Nothing -> empty
-
-insertIndividual :: Map Int XML.Place -> Map Int SSL.Individual -> WithSSID Ind.Individual -> Map Int SSL.Individual
-insertIndividual places' map' (WithSSID ssid individual) = insert ssid ssl_individual map'
- where ssl_individual = SSL.Individual { addresses = ssl_addresses
- , birth_dates = ssl_birth_dates
- , ids = ssl_ids
- , names = ssl_names
- , nationalities = ssl_nationalities
- }
-
- ssl_addresses = case Ind.addresses individual of
- Just addr -> foldl (insertAddress places') empty addr
- Nothing -> empty
-
- ssl_birth_dates = case Ind.birth_dates individual of
- Just bds -> foldl (insertFuncWithSSID $ liftQuality dateToOrdinal) empty bds
- Nothing -> empty
-
- ssl_ids = case Ind.ids individual of
- Just ids' -> foldl (insertFuncWithSSID id_number) empty ids'
- Nothing -> empty
-
- ssl_names = foldl (insertFuncWithSSID permutateNames) empty (Ind.names individual)
-
- ssl_nationalities = case Ind.nationalities individual of
- Just nat -> foldl (insertMaybeFuncWithSSID (readMaybe . T.unpack . country_code)) empty nat :: Map Int CountryCode
- Nothing -> empty
-
-insertMaybeFuncWithSSID :: (a -> Maybe b) -> Map Int b -> WithSSID a -> Map Int b
-insertMaybeFuncWithSSID func map' (WithSSID ssid x) = case func x of
- Just y -> insert ssid y map'
- Nothing -> map'
-
-insertFuncWithSSID :: (a -> b) -> Map Int b -> WithSSID a -> Map Int b
-insertFuncWithSSID func map' (WithSSID ssid x) = insert ssid (func x) map'
-
-insertWithSSID :: Map Int a -> WithSSID a -> Map Int a
-insertWithSSID map' (WithSSID ssid x) = insert ssid x map'
-
-
-
-insertAddress :: Map Int XML.Place -> Map Int (Quality SSL.Address) -> WithSSID (Quality XML.Address) -> Map Int (Quality SSL.Address)
-insertAddress places' map' (WithSSID ssid qual) = insert ssid gls_quality map'
- where ssl_address = removeQuality qual
- gls_quality = liftQuality (\_ -> gls_address) qual
- gls_address = SSL.Address { SSL.area = area'
- , SSL.country = country'
- , SSL.details = details'
- , SSL.location = location'
- , SSL.zip_code = XML.zip_code ssl_address
- }
-
- details' = case (XML.details ssl_address, XML.remark ssl_address) of
- (Just d, Just r) -> Just [d, r]
- (Just d, _ ) -> Just [d]
- (_ , Just r) -> Just [r]
- _ -> Nothing
-
- (area', country', location') =
- case lookup (place_id ssl_address) places' of
- Just place -> let
- gls_area = case (XML.area place, area_variant place) of
- (Just a, Just av) -> Just $ a:(maybeToList $ getVariant av)
- (Just a, _ ) -> Just [a]
- (_, Just av) -> case getVariant av of
- Just v -> Just [v]
- Nothing -> Nothing
- _ -> Nothing
- gls_country = case XML.country place of
- Just c -> (readMaybe . T.unpack . country_code) c :: Maybe CountryCode
- Nothing -> Nothing
- gls_location = case (XML.location place, location_variant place) of
- (Just l, Just lv) -> Just $ l:(maybeToList $ getVariant lv)
- (Just l, _ ) -> Just [l]
- (_ , Just lv) -> case getVariant lv of
- Just v -> Just [v]
- Nothing -> Nothing
- _ -> Nothing
- in
- (gls_area, gls_country, gls_location)
- Nothing -> (Nothing, Nothing, Nothing)
-
-
-dateToOrdinal :: Date -> (Year, Maybe DayOfYear)
-dateToOrdinal date' = case (month date', day date') of
- (Just m, Just d) -> let (y, doy) = toOrd m d in (y, Just doy)
- _ -> (year', Nothing)
- where year' = toEnum $ year date'
- toOrd month' day' = toOrdinalDate $ fromGregorian year' month' day'
-
-
--- All possible name combinations, including variants, in right order
--- FUTURE IDEA: check all name-parts seperately for similarity and add their score, probably need to add a similarity check between the name-parts to make sure they dont trigger on the same characters
-permutateNames :: Quality Name -> Quality [T.Text]
-permutateNames quality = liftQuality all_permutations quality
- where all_permutations n = map (T.intercalate " ") $ all_combinations $ [ name np : map variant (variants np) | np <- sortOn order (name_parts n) ]
- all_combinations ns = concatMap permutations $ concatMap subsequences $ foldr (liftM2 (:)) [[]] ns
diff --git a/src/KYCheck/SSL/Type.hs b/src/KYCheck/SSL/Type.hs
@@ -1,48 +0,0 @@
--- SPDX-FileCopyrightText: 2025 LNRS
---
--- SPDX-License-Identifier: AGPL-3.0-or-later
--- SPDX-License-Identifier: EUPL-1.2
-
-module KYCheck.SSL.Type
- ( Address(..)
- , Entity(..)
- , Individual(..)
- , Targets(..)
- ) where
-
-import Data.ISO3166_CountryCodes
-import Data.Map
-import Data.Text
-import Data.Time.Calendar.OrdinalDate
-
-import KYCheck.Type
-
-data Targets = Targets
- { start_date :: Maybe Day
- , individuals :: Map Int Individual
- , entities :: Map Int Entity
--- , objects :: Map Int UpdatedObject
- } deriving (Show, Eq)
-
-data Individual = Individual
- { addresses :: Map Int (Quality Address) -- Map (key = SSID) (elem = relevant address info)
- , birth_dates :: Map Int (Quality (Year, Maybe DayOfYear)) -- Map (key = SSID) (elem = date)
- , ids :: Map Int Text -- Map (key = SSID) (elem = id_number)
- , names :: Map Int (Quality [Text]) -- Map (key = SSID) (elem = all permutations of name)
- , nationalities :: Map Int CountryCode -- Map (key = SSID) (elem = ISO country-code)
- } deriving (Show, Eq)
-
-data Entity = Entity
- { entity_addresses :: Map Int (Quality Address) -- Map (key = SSID) (elem = relevant address info)
- , entity_dates :: Map Int (Quality (Year, Maybe DayOfYear))
- , entity_names :: Map Int (Quality [Text]) -- Map (key = SSID) (elem = all combinations of name)
- , other_info :: Map Int Text -- Map (key = SSID) (elem = registration number | email | phone)
- } deriving (Show, Eq)
-
-data Address = Address
- { country :: Maybe CountryCode -- country -> CountryCode
- , details :: Maybe [Text] -- street, number (w/ addition), address-details + remark elements
- , area :: Maybe [Text] -- area (maybe town_location, town_district or country_subdivision)
- , location :: Maybe [Text] -- location (maybe town_location, town_district or country_subdivision)
- , zip_code :: Maybe Text
- } deriving (Show, Eq)
diff --git a/src/KYCheck/SSL/XML/Entity/Parse.hs b/src/KYCheck/SSL/XML/Entity/Parse.hs
@@ -1,60 +0,0 @@
--- SPDX-FileCopyrightText: 2025 LNRS
---
--- SPDX-License-Identifier: AGPL-3.0-or-later
--- SPDX-License-Identifier: EUPL-1.2
-
-{-# LANGUAGE Arrows #-}
-{-# LANGUAGE BlockArguments #-}
-{-# LANGUAGE TemplateHaskell #-}
-{-# LANGUAGE ScopedTypeVariables #-}
-
-module KYCheck.SSL.XML.Entity.Parse
- ( getEntity
- ) where
-
-import Data.Tree.NTree.TypeDefs (NTree)
-
-import Text.XML.HXT.Core hiding (getName)
-
-import KYCheck.Type
-import KYCheck.SSL.XML.Type
-import KYCheck.SSL.XML.Entity.Type
-
-import KYCheck.SSL.XML.Helpers.Parse
-
-
-
-getEntity :: IOSLA (XIOState ()) (NTree XNode) TargetType
-getEntity = atElem "entity" >>>
- proc ent -> do
- WithSSID ssid identity <- getEntityIdentity -< ent
-
- justifications' <- getMaybeFunction (listA $ getElemWithSSID "justification" ) -< ent
- other_info' <- getMaybeFunction (listA $ getElemWithSSID "other-information") -< ent
- relations' <- getMaybeFunction (listA getRelation) -< ent
-
- returnA -< Ent $ WithSSID ssid $ Entity
- { addresses = id_addresses identity
- , dates = id_dates identity
- , names = id_names identity
- , justifications = justifications'
- , other_info = other_info'
- , relations = relations'
- }
-
-
-
-getEntityIdentity :: IOSLA (XIOState ()) (NTree XNode) (WithSSID EntityIdentity)
-getEntityIdentity = atElem "identity" >>>
- proc id' -> do
- ssid <- attrToInt "ssid" -< id'
-
- addresses' <- getMaybeFunction (listA getAddress) -< id'
- dates' <- getMaybeFunction (listA getDate) -< id'
- names' <- listA getName -< id'
-
- returnA -< WithSSID ssid $ EntityIdentity
- { id_addresses = addresses'
- , id_dates = dates'
- , id_names = names'
- }
diff --git a/src/KYCheck/SSL/XML/Entity/Type.hs b/src/KYCheck/SSL/XML/Entity/Type.hs
@@ -1,31 +0,0 @@
--- SPDX-FileCopyrightText: 2025 LNRS
---
--- SPDX-License-Identifier: AGPL-3.0-or-later
--- SPDX-License-Identifier: EUPL-1.2
-
-module KYCheck.SSL.XML.Entity.Type
- ( Entity(..)
- , EntityIdentity(..)
- ) where
-
-import Data.Text
-
-import KYCheck.Type
-import KYCheck.SSL.XML.Helpers.Type
-
-
-
-data Entity = Entity
- { addresses :: Maybe [WithSSID (Quality Address)]
- , dates :: Maybe [WithSSID (Quality Date)]
- , names :: [WithSSID (Quality Name)]
- , justifications :: Maybe [WithSSID Text]
- , other_info :: Maybe [WithSSID Text]
- , relations :: Maybe [WithSSID Relation]
- } deriving (Show, Eq)
-
-data EntityIdentity = EntityIdentity
- { id_addresses :: Maybe [WithSSID (Quality Address)]
- , id_dates :: Maybe [WithSSID (Quality Date)]
- , id_names :: [WithSSID (Quality Name)]
- } deriving (Show, Eq)
diff --git a/src/KYCheck/SSL/XML/Helpers/Parse.hs b/src/KYCheck/SSL/XML/Helpers/Parse.hs
@@ -1,244 +0,0 @@
--- SPDX-FileCopyrightText: 2025 LNRS
---
--- SPDX-License-Identifier: AGPL-3.0-or-later
--- SPDX-License-Identifier: EUPL-1.2
-
-{-# LANGUAGE Arrows #-}
-{-# LANGUAGE BlockArguments #-}
-{-# LANGUAGE TemplateHaskell #-}
-{-# LANGUAGE ScopedTypeVariables #-}
-
-module KYCheck.SSL.XML.Helpers.Parse
- ( atElem
- , atElemWithAttr
-
- , attrToInt
- , attrToMaybe
- , attrToMaybeInt
- , attrToText
-
- , elemToText
- , elemToInt
- , elemToMaybe
- , elemWithAttrToText
-
- , getMaybeFunction
- , getElemWithSSID
- , significant
-
- , getAddress
- , getCountry
- , getDate
- , getName
- , getRelation
- ) where
-
-import qualified Data.Text as T
-import Data.Tree.NTree.TypeDefs (NTree)
-
-import Text.XML.HXT.Core hiding (getName)
-
-import KYCheck.Type
-import KYCheck.SSL.XML.Type hiding (getVariant)
-
-
-
--- | Find element with matching tag_name
-atElem :: ArrowXml a => String -> a (NTree XNode) XmlTree
-atElem elem' = deep ( isElem >>> hasName elem' )
-
--- | Find a certain element with a specific attribute pair (tag and value)
-atElemWithAttr :: ArrowXml a => String -> String -> String -> a (NTree XNode) XmlTree
-atElemWithAttr elem' attr_name attr_val = deep ( isElem >>> hasName elem' >>> hasAttrValue attr_name (== attr_val) )
-
-
-
--- | Get value of certain attribute and read it as an Int
-attrToInt :: ArrowXml a => String -> a (NTree XNode) Int
-attrToInt attr' = arr read <<< getAttrValue attr'
-
--- | Get value of possible attribute
-attrToMaybe :: ArrowXml a => String -> a (NTree XNode) (Maybe String)
-attrToMaybe attr' = withDefault ( arr Just <<< isA significant <<< getAttrValue attr' ) Nothing
-
--- | Get value of possible attribute and read it as an Int
-attrToMaybeInt :: ArrowXml a => String -> a (NTree XNode) (Maybe Int)
-attrToMaybeInt attr' = withDefault ( arr ( Just . read ) <<< isA significant <<< getAttrValue attr' ) Nothing
-
--- | Get value of certain attribute and pack it as Text
-attrToText :: ArrowXml a => String -> a (NTree XNode) T.Text
-attrToText attr' = arr T.pack <<< getAttrValue attr'
-
-
-
--- | Get value of certain element and read it as an Int
-elemToInt :: ArrowXml a => String -> a (NTree XNode) Int
-elemToInt elem' = arr read <<< getText <<< getChildren <<< atElem elem'
-
--- | Get value of a possible element and pack is as Maybe Text
-elemToMaybe :: ArrowXml a => String -> a (NTree XNode) (Maybe T.Text)
-elemToMaybe elem' = withDefault ( arr ( Just . T.pack ) <<< isA significant <<< getText <<< getChildren <<< atElem elem' ) Nothing
-
--- | Get value of certain element and pack it as Text
-elemToText :: ArrowXml a => String -> a (NTree XNode) T.Text
-elemToText elem' = arr T.pack <<< getText <<< getChildren <<< atElem elem'
-
--- | Get value of certain element with specific attribute pair (tag and value) and pack it as Text
-elemWithAttrToText :: ArrowXml a => String -> String -> String -> a (NTree XNode) T.Text
-elemWithAttrToText elem' attr_name attr_val = arr T.pack <<< getText <<< getChildren <<< atElemWithAttr elem' attr_name attr_val
-
-
-
--- | Check if a certain xml tag contains any significant values
-significant :: String -> Bool
-significant = not . all (`elem` " \n\r\t")
-
--- | Get a parser of type a, return a parser of type Maybe a
-getMaybeFunction :: IOSLA (XIOState ()) (NTree XNode) a -> IOSLA (XIOState ()) (NTree XNode) (Maybe a)
-getMaybeFunction f = do withDefault ( arr Just <<< f ) Nothing
-
--- | Get an element with SSID attribute and return WithSSID Text
-getElemWithSSID :: String -> IOSLA (XIOState ()) (NTree XNode) (WithSSID T.Text)
-getElemWithSSID elem' = atElem elem' >>>
- proc x -> do
- ssid <- attrToInt "ssid" -< x
-
- val' <- getText <<< getChildren -< x
-
- returnA -< WithSSID ssid (T.pack val')
-
-
-
-
-
-getAddress :: IOSLA (XIOState ()) (NTree XNode) (WithSSID (Quality Address))
-getAddress = atElem "address" >>>
- proc addr -> do
- ssid <- attrToInt "ssid" -< addr
- quality <- getAttrValue "quality" -< addr
-
- c_o' <- elemToMaybe "c-o" -< addr
- details' <- elemToMaybe "address-details" -< addr
- place_id' <- attrToInt "place-id" -< addr
- p_o_box' <- elemToMaybe "p-o-box" -< addr
- remark' <- elemToMaybe "remark" -< addr
- zip_code' <- elemToMaybe "zip-code" -< addr
-
- returnA -< WithSSID ssid $ stringToQuality quality $ Address
- { c_o = c_o'
- , details = details'
- , place_id = place_id'
- , p_o_box = p_o_box'
- , remark = remark'
- , zip_code = zip_code'
- }
-
-
-
-getCountry :: String -> String -> IOSLA (XIOState ()) (NTree XNode) Country
-getCountry elem' attr' = atElem elem' >>>
- proc country' -> do
- name' <- arr T.pack <<< getText <<< getChildren -< country'
- code' <- attrToText attr' -< country'
-
- returnA -< Country
- { country_name = name'
- , country_code = code'
- }
-
-
-
-getDate :: IOSLA (XIOState ()) (NTree XNode) (WithSSID (Quality Date))
-getDate = atElem "day-month-year" >>>
- proc date' -> do
- ssid <- attrToInt "ssid" -< date'
- quality <- getAttrValue "quality" -< date'
-
- day' <- attrToMaybeInt "day" -< date'
- month' <- attrToMaybeInt "month" -< date'
- year' <- attrToMaybeInt "year" -< date'
- calendar' <- getAttrValue "calendar" -< date'
-
- returnA -< WithSSID ssid $ stringToQuality quality $ Date
- { day = day'
- , month = month'
- , year = case year' of Just y -> y; Nothing -> 2025;
- , calendar = T.pack calendar'
- }
-
-
-
-getName :: IOSLA (XIOState ()) (NTree XNode) (WithSSID (Quality Name))
-getName = atElem "name" >>>
- proc name' -> do
- ssid <- attrToInt "ssid" -< name'
- quality <- getAttrValue "quality" -< name'
-
- name_type' <- getAttrValue "name-type" -< name'
- name_parts' <- listA getNamePart -< name'
-
- returnA -< WithSSID ssid $ stringToQuality quality $ Name
- { name_parts = name_parts'
- , name_type = case name_type' of
- "primary-name" -> PrimaryName
- "alias" -> Alias
- "formerly-known-as" -> FormerlyKnownAs
- x -> (UnknownNameType . T.pack) x
- }
-
-getNamePart :: IOSLA (XIOState ()) (NTree XNode) NamePart
-getNamePart = atElem "name-part" >>>
- proc name_part -> do
- name' <- elemToText "value" -< name_part
- order' <- attrToInt "order" -< name_part
- name_part_type' <- getAttrValue "name-part-type" -< name_part
- variants' <- listA getSpellingVariant -< name_part
-
- returnA -< NamePart
- { name = name'
- , order = order'
- , variants = variants'
- , name_part_type = case name_part_type' of
- "family-name" -> FamilyName
- "father-name" -> FatherName
- "further-given-name" -> FurtherGivenName
- "given-name" -> GivenName
- "grand-father-name" -> GrandFatherName
- "maiden-name" -> MaidenName
- "suffix" -> Suffix
- "title" -> Title
- "tribal-name" -> TribalName
- "whole-name" -> WholeName
- "other" -> OtherNPT
- x -> (UnknownNamePartType . T.pack) x
- }
-
-getSpellingVariant :: IOSLA (XIOState ()) (NTree XNode) SpellingVariant
-getSpellingVariant = atElem "spelling-variant" >>>
- proc spelling_variant -> do
- language' <- getAttrValue "lang" -< spelling_variant
- script' <- getAttrValue "script" -< spelling_variant
- variant' <- getText <<< getChildren -< spelling_variant
-
- returnA -< SpellingVariant
- { language = T.pack language'
- , script = T.pack script'
- , variant = T.pack variant'
- }
-
-
-
-getRelation :: IOSLA (XIOState ()) (NTree XNode) (WithSSID Relation)
-getRelation = atElem "relation" >>>
- proc rel -> do
- ssid <- attrToInt "ssid" -< rel
-
- rel_target <- attrToInt "target-id" -< rel
- rel_type <- getAttrValue "relation-type" -< rel
-
- returnA -< WithSSID ssid $ Relation
- { target_id = rel_target
- , relation_type = case rel_type of
- "related-to" -> RelatedTo
- x -> (UnknownRelation . T.pack) x
- }
diff --git a/src/KYCheck/SSL/XML/Helpers/Type.hs b/src/KYCheck/SSL/XML/Helpers/Type.hs
@@ -1,97 +0,0 @@
--- SPDX-FileCopyrightText: 2025 LNRS
---
--- SPDX-License-Identifier: AGPL-3.0-or-later
--- SPDX-License-Identifier: EUPL-1.2
-
-module KYCheck.SSL.XML.Helpers.Type
- ( Address(..)
- , Country(..)
- , Date(..)
- , Name(..)
- , NamePart(..)
- , NamePartType(..)
- , NameType(..)
- , Relation(..)
- , RelationType(..)
- , SpellingVariant(..)
- , WithSSID(..)
- ) where
-
-import Data.Text
-
-import KYCheck.Type
-
-
-
-data Address = Address
- { c_o :: Maybe Text
- , details :: Maybe Text
- , p_o_box :: Maybe Text
- , place_id :: Int
- , remark :: Maybe Text
- , zip_code :: Maybe Text
- } deriving (Show, Eq)
-
-
-
-data Country = Country
- { country_name :: Text
- , country_code :: Text
- } deriving (Show, Eq)
-
-
-
-data Date = Date
- { day :: Maybe Int
- , month :: Maybe Int
- , year :: Int
- , calendar :: Text
- } deriving (Show, Eq)
-
-
-
-data Name = Name
- { name_type :: NameType
- , name_parts :: [NamePart]
- } deriving (Show, Eq)
-
-data NameType = PrimaryName
- | Alias
- | FormerlyKnownAs
- | UnknownNameType Text deriving (Show, Eq)
-
-data NamePart = NamePart
- { name :: Text
- , order :: Int
- , name_part_type :: NamePartType
- , variants :: [SpellingVariant]
- } deriving (Show, Eq)
-
-data NamePartType = FamilyName
- | FatherName
- | FurtherGivenName
- | GivenName
- | GrandFatherName
- | MaidenName
- | Suffix
- | Title
- | TribalName
- | WholeName
- | OtherNPT
- | UnknownNamePartType Text deriving (Show, Eq)
-
-data SpellingVariant = SpellingVariant
- { language :: Text
- , script :: Text
- , variant :: Text
- } deriving (Show, Eq)
-
-
-
-data Relation = Relation
- { relation_type :: RelationType
- , target_id :: Int
- } deriving (Show, Eq)
-
-data RelationType = RelatedTo
- | UnknownRelation Text deriving (Show, Eq)
diff --git a/src/KYCheck/SSL/XML/Individual/Parse.hs b/src/KYCheck/SSL/XML/Individual/Parse.hs
@@ -1,119 +0,0 @@
--- SPDX-FileCopyrightText: 2025 LNRS
---
--- SPDX-License-Identifier: AGPL-3.0-or-later
--- SPDX-License-Identifier: EUPL-1.2
-
-{-# LANGUAGE Arrows #-}
-{-# LANGUAGE BlockArguments #-}
-{-# LANGUAGE TemplateHaskell #-}
-{-# LANGUAGE ScopedTypeVariables #-}
-
-module KYCheck.SSL.XML.Individual.Parse
- ( getIndividual
- ) where
-
-import qualified Data.Text as T
-
-import Data.Tree.NTree.TypeDefs (NTree)
-
-import Text.XML.HXT.Core hiding (getName)
-
-import KYCheck.Type
-import KYCheck.SSL.XML.Type
-import KYCheck.SSL.XML.Individual.Type
-import KYCheck.SSL.XML.Helpers.Parse
-
-
-
-getIndividual :: IOSLA (XIOState ()) (NTree XNode) TargetType
-getIndividual = atElem "individual" >>>
- proc ind -> do
- WithSSID ssid identity <- getIndividualIdentity -< ind
-
- sex' <- attrToMaybe "sex" -< ind
- justifications' <- getMaybeFunction (listA $ getElemWithSSID "justification" ) -< ind
- other_info' <- getMaybeFunction (listA $ getElemWithSSID "other-information") -< ind
- relations' <- getMaybeFunction (listA getRelation) -< ind
-
- returnA -< Ind $ WithSSID ssid $ Individual
- { addresses = id_addresses identity
- , birth_dates = id_birth_dates identity
- , ids = id_ids identity
- , names = id_names identity
- , nationalities = id_nationalities identity
- , sex = case sex' of
- Just "male" -> Just Male
- Just "female" -> Just Female
- Just x -> (Just . UnknownSex . T.pack) x
- Nothing -> Nothing
- , justifications = justifications'
- , other_info = other_info'
- , relations = relations'
- }
-
-
-
-getIndividualIdentity :: IOSLA (XIOState ()) (NTree XNode) (WithSSID IndividualIdentity)
-getIndividualIdentity = atElem "identity" >>>
- proc identity -> do
- ssid <- attrToInt "ssid" -< identity
-
- addresses' <- getMaybeFunction (listA getAddress) -< identity
- birth_dates' <- getMaybeFunction (listA getDate) -< identity
- ids' <- getMaybeFunction (listA getIdentificationDocument) -< identity
- names' <- listA getName -< identity
- nationalities' <- getMaybeFunction (listA getNationality) -< identity
-
- returnA -< WithSSID ssid $ IndividualIdentity
- { id_addresses = addresses'
- , id_birth_dates = birth_dates'
- , id_ids = ids'
- , id_names = names'
- , id_nationalities = nationalities'
- }
-
-
-
-getIdentificationDocument :: IOSLA (XIOState ()) (NTree XNode) (WithSSID IdentificationDocument)
-getIdentificationDocument = atElem "identification-document" >>>
- proc doc -> do
- ssid <- attrToInt "ssid" -< doc
-
- number <- elemToText "number" -< doc
- date_of_issue <- elemToMaybe "date-of-issue" -< doc
- expiry_date <- elemToMaybe "expiry-date" -< doc
- remark' <- elemToMaybe "remark" -< doc
- id_type' <- getAttrValue "document-type" -< doc
- -- place_of_issue <- attrToMaybeInt "place-id" <<< atElem "place-of-issue" -< doc
- country' <- getCountry "issuer" "code" -< doc
-
- returnA -< WithSSID ssid $ IdentificationDocument
- { id_number = number
- , id_issuer = country'
- , id_remark = remark'
- , id_date_of_issue = date_of_issue
- -- , doc_place_of_issue = place_of_issue
- , id_expiry_date = expiry_date
- , id_type = case id_type' of
- "diplomatic-passport" -> DiplomaticPassport
- "driving-license" -> DrivingLicense
- "driving-permit" -> DrivingPermit
- "id-card" -> IDCard
- "passport" -> Passport
- "residence-permit" -> ResidencePermit
- "travel-document" -> TravelDocument
- "other" -> OtherIDType
- x -> (UnknownIDType . T.pack) x
-
- }
-
-
-
-getNationality :: IOSLA (XIOState ()) (NTree XNode) (WithSSID Country)
-getNationality = atElem "nationality" >>>
- proc n -> do
- ssid <- attrToInt "ssid" -< n
-
- country' <- getCountry "country" "iso-code" -< n
-
- returnA -< WithSSID ssid country'
diff --git a/src/KYCheck/SSL/XML/Individual/Type.hs b/src/KYCheck/SSL/XML/Individual/Type.hs
@@ -1,61 +0,0 @@
--- SPDX-FileCopyrightText: 2025 LNRS
---
--- SPDX-License-Identifier: AGPL-3.0-or-later
--- SPDX-License-Identifier: EUPL-1.2
-
-module KYCheck.SSL.XML.Individual.Type
- ( IdentificationDocument(..)
- , IDType(..)
- , Individual(..)
- , IndividualIdentity(..)
- , Sex(..)
- ) where
-
-import Data.Text
-
-import KYCheck.Type
-import KYCheck.SSL.XML.Helpers.Type
-
-data Individual = Individual
- { addresses :: Maybe [WithSSID (Quality Address)]
- , birth_dates :: Maybe [WithSSID (Quality Date)]
- , ids :: Maybe [WithSSID (IdentificationDocument)]
- , names :: [WithSSID (Quality Name)]
- , nationalities :: Maybe [WithSSID Country]
- , sex :: Maybe Sex
- , justifications :: Maybe [WithSSID Text]
- , other_info :: Maybe [WithSSID Text]
- , relations :: Maybe [WithSSID Relation]
- } deriving (Show, Eq)
-
-data IndividualIdentity = IndividualIdentity
- { id_addresses :: Maybe [WithSSID (Quality Address)]
- , id_birth_dates :: Maybe [WithSSID (Quality Date)]
- , id_ids :: Maybe [WithSSID IdentificationDocument]
- , id_names :: [WithSSID (Quality Name)]
- , id_nationalities :: Maybe [WithSSID Country]
- } deriving (Show, Eq)
-
-data IdentificationDocument = IdentificationDocument
- { id_number :: Text
- , id_issuer :: Country
- , id_date_of_issue :: Maybe Text
- -- , doc_place_of_issue :: Maybe Int
- , id_expiry_date :: Maybe Text
- , id_remark :: Maybe Text
- , id_type :: IDType
- } deriving (Show, Eq)
-
-data IDType = DiplomaticPassport
- | DrivingLicense
- | DrivingPermit
- | IDCard
- | Passport
- | ResidencePermit
- | TravelDocument
- | OtherIDType
- | UnknownIDType Text deriving (Show, Eq)
-
-data Sex = Male
- | Female
- | UnknownSex Text deriving (Show, Eq)
diff --git a/src/KYCheck/SSL/XML/Object/Parse.hs b/src/KYCheck/SSL/XML/Object/Parse.hs
@@ -1,53 +0,0 @@
--- SPDX-FileCopyrightText: 2025 LNRS
---
--- SPDX-License-Identifier: AGPL-3.0-or-later
--- SPDX-License-Identifier: EUPL-1.2
-
-{-# LANGUAGE Arrows #-}
-{-# LANGUAGE BlockArguments #-}
-{-# LANGUAGE TemplateHaskell #-}
-{-# LANGUAGE ScopedTypeVariables #-}
-
-module KYCheck.SSL.XML.Object.Parse
- ( getObject
- ) where
-
-import qualified Data.Text as T
-import Data.Tree.NTree.TypeDefs (NTree)
-
-import Text.XML.HXT.Core hiding (getName)
-
-import KYCheck.Type
-import KYCheck.SSL.XML.Type
-import KYCheck.SSL.XML.Object.Type
-
-import KYCheck.SSL.XML.Helpers.Parse
-
-
-
-getObject :: IOSLA (XIOState ()) (NTree XNode) TargetType
-getObject = atElem "object" >>>
- proc object -> do
- WithSSID ssid names' <- getObjectIdentity -< object
-
- object_type' <- getAttrValue "object-type" -< object
- other_info' <- getMaybeFunction (listA $ getElemWithSSID "other-information") -< object
-
- returnA -< Obj $ WithSSID ssid $ Object
- { names = names'
- , other_info = other_info'
- , object_type = case object_type' of
- "vessel" -> Vessel
- x -> (UnknownObject . T.pack) x
- }
-
-
-
-getObjectIdentity :: IOSLA (XIOState ()) (NTree XNode) (WithSSID [WithSSID (Quality Name)])
-getObjectIdentity = atElem "identity" >>>
- proc id' -> do
- ssid <- attrToInt "ssid" -< id'
-
- names' <- listA getName -< id'
-
- returnA -< WithSSID ssid names'
diff --git a/src/KYCheck/SSL/XML/Object/Type.hs b/src/KYCheck/SSL/XML/Object/Type.hs
@@ -1,25 +0,0 @@
--- SPDX-FileCopyrightText: 2025 LNRS
---
--- SPDX-License-Identifier: AGPL-3.0-or-later
--- SPDX-License-Identifier: EUPL-1.2
-
-module KYCheck.SSL.XML.Object.Type
- ( Object(..)
- , ObjectType(..)
- ) where
-
-import Data.Text
-
-import KYCheck.Type
-import KYCheck.SSL.XML.Helpers.Type
-
-
-
-data Object = Object
- { object_type :: ObjectType
- , names :: [WithSSID (Quality Name)]
- , other_info :: Maybe [WithSSID Text]
- } deriving (Show, Eq)
-
-data ObjectType = Vessel
- | UnknownObject Text deriving (Show, Eq)
diff --git a/src/KYCheck/SSL/XML/Parse.hs b/src/KYCheck/SSL/XML/Parse.hs
@@ -1,125 +0,0 @@
--- SPDX-FileCopyrightText: 2025 LNRS
---
--- SPDX-License-Identifier: AGPL-3.0-or-later
--- SPDX-License-Identifier: EUPL-1.2
-
-{-# LANGUAGE Arrows #-}
-{-# LANGUAGE BlockArguments #-}
-{-# LANGUAGE TemplateHaskell #-}
-{-# LANGUAGE ScopedTypeVariables #-}
-
-module KYCheck.SSL.XML.Parse
- ( parseSwissSanctionsList
- ) where
-
-import Data.Tree.NTree.TypeDefs (NTree)
-
-import Text.XML.HXT.Core
-
-import KYCheck.Type
-import KYCheck.SSL.XML.Type hiding (getVariant)
-
-import KYCheck.SSL.XML.Entity.Parse
-import KYCheck.SSL.XML.Helpers.Parse
-import KYCheck.SSL.XML.Individual.Parse
-import KYCheck.SSL.XML.Object.Parse
-import KYCheck.SSL.XML.Place.Parse
-
-
-
-parseSwissSanctionsList :: FilePath -> IO SwissSanctionsList
-parseSwissSanctionsList fp = do
- [ sanction_list ] <- runX ( readDocument xmlConfig fp >>> getSwissSanctionsList )
- return sanction_list
-
--- | Config settings for xml parsing
-xmlConfig :: SysConfigList
-xmlConfig = [ withRemoveWS yes
- , withValidate no
- , withParseHTML no
- ]
-
-
-
-getSwissSanctionsList :: IOSLA (XIOState ()) (NTree XNode) SwissSanctionsList
-getSwissSanctionsList = atElem "swiss-sanctions-list" >>>
- proc ssl -> do
- ssl_date <- attrToText "date" -< ssl
- ssl_sanction_programs <- listA getSanctionProgram -< ssl
- ssl_targets <- listA getTarget -< ssl
- ssl_places <- listA getPlace -< ssl
-
- returnA -< SwissSanctionsList
- { date = ssl_date
- , sanction_programs = ssl_sanction_programs
- , targets = ssl_targets
- , places = ssl_places
- }
-
-
-
-getSanctionProgram :: IOSLA (XIOState ()) (NTree XNode) (WithSSID SanctionProgram)
-getSanctionProgram = atElem "sanctions-program" >>>
- proc sanction_program -> do
- ssid <- attrToInt "ssid" -< sanction_program
-
- program_key' <- getTranslations "program-key" -< sanction_program
- program_name' <- getTranslations "program-name" -< sanction_program
- sanctions_set' <- getTranslationsWithSSID "sanctions-set" -< sanction_program
- version_date' <- attrToText "version-date" -< sanction_program
- predecessor_version_date' <- attrToText "predecessor-version-date" -< sanction_program
- origin' <- elemToMaybe "origin" -< sanction_program
-
- returnA -< WithSSID ssid $ SanctionProgram
- { program_key = program_key'
- , program_name = program_name'
- , sanctions_set = sanctions_set'
- , version_date = version_date'
- , predecessor_version_date = predecessor_version_date'
- , origin = origin'
- }
-
-
-
-getTranslations :: String -> IOSLA (XIOState ()) (NTree XNode) Translations
-getTranslations elem' =
- proc translations -> do
- eng <- elemWithAttrToText elem' "lang" "eng" -< translations
- ger <- elemWithAttrToText elem' "lang" "ger" -< translations
- fre <- elemWithAttrToText elem' "lang" "fre" -< translations
- ita <- elemWithAttrToText elem' "lang" "ita" -< translations
-
- returnA -< Translations
- { english = eng
- , french = fre
- , german = ger
- , italian = ita
- }
-
-
-
-getTranslationsWithSSID :: String -> IOSLA (XIOState ()) (NTree XNode) (WithSSID Translations)
-getTranslationsWithSSID elem' =
- proc t -> do
- ssid <- attrToInt "ssid" <<< atElemWithAttr elem' "lang" "eng" -< t
-
- translations <- getTranslations elem' -< t
-
- returnA -< WithSSID ssid translations
-
-
-
-getTarget :: IOSLA (XIOState ()) (NTree XNode) (WithSSID Target)
-getTarget = processTopDown (filterA $ neg (isElem >>> hasName "modification")) >>> atElem "target" >>>
- proc target -> do
- ssid <- attrToInt "ssid" -< target
-
- sanctions_set_id' <- elemToInt "sanctions-set-id" -< target
- foreign_identifier' <- elemToMaybe "foreign-identifier" -< target
- target' <- getIndividual <+> getEntity <+> getObject -< target
-
- returnA -< WithSSID ssid $ Target
- { sanctions_set_id = sanctions_set_id'
- , foreign_identifier = foreign_identifier'
- , target_type = target'
- }
diff --git a/src/KYCheck/SSL/XML/Place/Parse.hs b/src/KYCheck/SSL/XML/Place/Parse.hs
@@ -1,57 +0,0 @@
--- SPDX-FileCopyrightText: 2025 LNRS
---
--- SPDX-License-Identifier: AGPL-3.0-or-later
--- SPDX-License-Identifier: EUPL-1.2
-
-{-# LANGUAGE Arrows #-}
-{-# LANGUAGE BlockArguments #-}
-{-# LANGUAGE TemplateHaskell #-}
-{-# LANGUAGE ScopedTypeVariables #-}
-
-module KYCheck.SSL.XML.Place.Parse
- ( getPlace
- ) where
-
-import qualified Data.Text as T
-import Data.Tree.NTree.TypeDefs (NTree)
-
-import Text.XML.HXT.Core hiding (getName)
-
-import KYCheck.Type
-import KYCheck.SSL.XML.Type hiding (getVariant)
-
-import KYCheck.SSL.XML.Helpers.Parse
-
-
-
-getPlace :: IOSLA (XIOState ()) (NTree XNode) (WithSSID Place)
-getPlace = atElem "place" >>>
- proc p -> do
- ssid <- attrToInt "ssid" -< p
-
- area' <- elemToMaybe "area" -< p
- location' <- elemToMaybe "location" -< p
- area_variant' <- withDefault ( arr Just <<< getVariant "location-variant" ) Nothing -< p
- location_variant' <- withDefault ( arr Just <<< getVariant "area-variant" ) Nothing -< p
- country' <- withDefault ( arr Just <<< getCountry "country" "iso-code" ) Nothing -< p
-
- returnA -< WithSSID ssid $ Place
- { area = area'
- , area_variant = area_variant'
- , country = country'
- , location = location'
- , location_variant = location_variant'
- }
-
-
-
-getVariant :: String -> IOSLA (XIOState ()) (NTree XNode) Variant
-getVariant elem' = atElem elem' >>>
- proc x -> do
- value <- arr T.pack <<< getText <<< getChildren -< x
- variant_type <- getAttrValue "variant-type" -< x
-
- returnA -< case variant_type of
- "formerly-known-as" -> FKA value
- "spelling-variant" -> Spelling value
- _ -> Unknown value
diff --git a/src/KYCheck/SSL/XML/Place/Type.hs b/src/KYCheck/SSL/XML/Place/Type.hs
@@ -1,37 +0,0 @@
--- SPDX-FileCopyrightText: 2025 LNRS
---
--- SPDX-License-Identifier: AGPL-3.0-or-later
--- SPDX-License-Identifier: EUPL-1.2
-
-module KYCheck.SSL.XML.Place.Type
- ( Place(..)
- , Variant(..)
- , getVariant
- ) where
-
-import Data.Text
-
-import KYCheck.SSL.XML.Helpers.Type
-
-
-
--- Place contains information about a specific country, location or area
-data Place = Place
- { area :: Maybe Text
- , area_variant :: Maybe Variant
- , country :: Maybe Country
- , location :: Maybe Text
- , location_variant :: Maybe Variant
- } deriving (Show, Eq)
-
-
-
-data Variant = Spelling Text
- | FKA Text
- | Unknown Text deriving (Show, Eq)
-
-getVariant :: Variant -> Maybe Text
-getVariant var = case var of
- Spelling txt -> Just txt
- FKA txt -> Just txt
- _ -> Nothing
diff --git a/src/KYCheck/SSL/XML/Type.hs b/src/KYCheck/SSL/XML/Type.hs
@@ -1,89 +0,0 @@
--- SPDX-FileCopyrightText: 2025 LNRS
---
--- SPDX-License-Identifier: AGPL-3.0-or-later
--- SPDX-License-Identifier: EUPL-1.2
-
-module KYCheck.SSL.XML.Type
- ( Address(..)
- , Country(..)
- , Date(..)
- , getNames
- , getSSID
- , getVariant
- , IdentificationDocument(..)
- , IDType(..)
- , Name(..)
- , NamePart(..)
- , NamePartType(..)
- , NameType(..)
- , Place(..)
- , Relation(..)
- , RelationType(..)
- , SanctionProgram(..)
- , Sex(..)
- , SpellingVariant(..)
- , SwissSanctionsList(..)
- , Target(..)
- , TargetType(..)
- , Translations(..)
- , Variant(..)
- , WithSSID(..)
- ) where
-
-import Data.Text
-
-import KYCheck.Type
-import KYCheck.SSL.XML.Helpers.Type
-import KYCheck.SSL.XML.Entity.Type as Ent
-import KYCheck.SSL.XML.Individual.Type as Ind
-import KYCheck.SSL.XML.Object.Type as Obj
-
-import KYCheck.SSL.XML.Place.Type
-
-
-
-data SwissSanctionsList = SwissSanctionsList
- { date :: Text
- , sanction_programs :: [WithSSID SanctionProgram]
- , targets :: [WithSSID Target]
- , places :: [WithSSID Place]
- } deriving (Show, Eq)
-
-
-
--- SanctionProgram contains the specifics of the program
-data SanctionProgram = SanctionProgram
- { program_key :: Translations
- , program_name :: Translations
- , sanctions_set :: WithSSID Translations
- , version_date :: Text
- , predecessor_version_date :: Text
- , origin :: Maybe Text
- } deriving (Show, Eq)
-
-data Translations = Translations
- { english :: Text
- , french :: Text
- , german :: Text
- , italian :: Text
- } deriving (Show, Eq)
-
-
-
--- Target contains the information about a sanctioned individual/entity/object
-data Target = Target
- { sanctions_set_id :: Int
- , foreign_identifier :: Maybe Text
- , target_type :: TargetType
- } deriving (Show, Eq)
-
-data TargetType = Ind (WithSSID Individual)
- | Ent (WithSSID Entity)
- | Obj (WithSSID Object) deriving (Show, Eq)
-
-
-
-getNames :: TargetType -> [WithSSID (Quality Name)]
-getNames (Ind (WithSSID _ ind)) = Ind.names ind
-getNames (Ent (WithSSID _ ent)) = Ent.names ent
-getNames (Obj (WithSSID _ obj)) = Obj.names obj
diff --git a/src/KYCheck/Type.hs b/src/KYCheck/Type.hs
@@ -1,134 +0,0 @@
--- SPDX-FileCopyrightText: 2025 LNRS
---
--- SPDX-License-Identifier: AGPL-3.0-or-later
--- SPDX-License-Identifier: EUPL-1.2
-
-
-{-# LANGUAGE DeriveGeneric #-}
-{-# LANGUAGE RecordWildCards #-}
-{-# LANGUAGE OverloadedStrings #-}
-{-# LANGUAGE PatternSynonyms #-}
-{-# LANGUAGE ViewPatterns #-}
-
-module KYCheck.Type
- ( getSSID
- , liftQuality
- , Quality(..)
- , removeQuality
- , removeSSID
- , stringToQuality
- , WithSSID(..)
-
- , Day'(..)
- , pattern YMD
-
- , CommandLine(..)
- , Config(..)
- , TomlConfig(..)
- , Verbosity(..)
- ) where
-
-import GHC.Generics (Generic)
-
-import Data.Aeson (ToJSON(..), FromJSON(..), withText)
-import Data.Text (unpack)
-import Data.Time.Calendar
-import Data.Time.Format (defaultTimeLocale, parseTimeM)
-
-
-
-data Quality a = Good a
- | Low a
- | UnknownQuality a deriving (Show, Eq)
-
-liftQuality :: (a -> b) -> Quality a -> Quality b
-liftQuality func qual = case qual of
- Good x -> Good $ func x
- Low x -> Low $ func x
- UnknownQuality x -> UnknownQuality $ func x
-
-removeQuality :: Quality a -> a
-removeQuality (Good x) = x
-removeQuality (Low x) = x
-removeQuality (UnknownQuality x) = x
-
-stringToQuality :: String -> a -> Quality a
-stringToQuality quality value = case quality of
- "good" -> Good value
- "low" -> Low value
- _ -> UnknownQuality value
-
-data WithSSID a = WithSSID Int a deriving (Show, Eq)
-
-getSSID :: WithSSID a -> Int
-getSSID (WithSSID n _) = n
-
-removeSSID :: WithSSID a -> a
-removeSSID (WithSSID _ x) = x
-
-
-newtype Day' = Day' Day deriving (Show, Eq, Generic)
-
-instance FromJSON Day' where
- parseJSON = withText "birthdate" $ \t ->
- case parseTimeM False defaultTimeLocale "%Y-%-m-%-d" (unpack t) of
- Just d -> pure $ Day' d
- Nothing -> fail $ "Invalid Day format: " ++ unpack t
-
-instance ToJSON Day'
-
-pattern YMD :: Year -> MonthOfYear -> DayOfMonth -> Day'
-pattern YMD y m d <-
- Day' (toGregorian -> (y,m,d))
- where
- YMD y m d = Day' $ fromGregorian y m d
-
-{-# COMPLETE YMD #-}
-
-
--- | Data type containing all configuration information (kycheck.conf)
-data Config = Config
- { verbosity :: Verbosity
- , ssl_location :: FilePath
- , threshold_ratio :: Float
- , threshold_points :: Float
- , threshold_confidence :: Float
- , perfect_points :: Float
- , weight_address :: Float
- , weight_date :: Float
- , weight_id :: Float
- , weight_name :: Float
- , weight_nationality :: Float
- } deriving (Show, Eq, Generic)
-
-data Verbosity = Test | Silent | Info | Errors | Debug deriving (Show, Eq, Generic, Ord)
-
-data TomlConfig = TomlConfig
- { toml_verbosity :: Verbosity
- , toml_ssl_location :: FilePath
- , toml_threshold_ratio :: Float
- , toml_threshold_points :: Float
- , toml_threshold_confidence :: Float
- , toml_perfect_points :: Float
- , toml_weight_address :: Float
- , toml_weight_date :: Float
- , toml_weight_id :: Float
- , toml_weight_name :: Float
- , toml_weight_nationality :: Float
- } deriving (Show, Eq, Generic)
-
--- | Data type for user configuration via commandline
-data CommandLine = CommandLine
- { cl_verbosity :: Maybe Verbosity
- , cl_config_location :: FilePath
- , cl_ssl_location :: Maybe FilePath
- , cl_threshold_ratio :: Maybe Float
- , cl_threshold_points :: Maybe Float
- , cl_threshold_confidence :: Maybe Float
- , cl_perfect_points :: Maybe Float
- , cl_weight_address :: Maybe Float
- , cl_weight_date :: Maybe Float
- , cl_weight_id :: Maybe Float
- , cl_weight_name :: Maybe Float
- , cl_weight_nationality :: Maybe Float
- } deriving (Show, Eq, Generic)
diff --git a/src/Robocop/Check.hs b/src/Robocop/Check.hs
@@ -0,0 +1,310 @@
+-- SPDX-FileCopyrightText: 2025 LNRS
+--
+-- SPDX-License-Identifier: AGPL-3.0-or-later
+-- SPDX-License-Identifier: EUPL-1.2
+
+{-# LANGUAGE OverloadedStrings #-}
+
+module Robocop.Check
+ ( checkAddress
+ , checkBirthDate
+ , checkCountryCode
+ , checkEntity
+ , checkID
+ , checkNames
+ , checkPersons
+ , compareFullDate
+ , multFloats
+ , Score(..)
+ ) where
+
+import Data.ISO3166_CountryCodes
+import Data.List (permutations, subsequences)
+import Data.Maybe
+import Data.Map (Map, toList)
+import Data.Ratio
+
+import Data.Text (intercalate, pack, snoc, Text)
+import qualified Data.Text as T
+import Data.Text.Metrics
+
+import Data.Time.Calendar
+import Data.Time.Calendar.OrdinalDate
+
+import Robocop.Type
+import Robocop.SSL.Type as SSL
+import Robocop.GLS.Type as GLS
+
+import Prelude hiding (lines)
+
+data Score = Score
+ { match_quality :: Float
+ , confidence :: Float
+ , expiration :: Int
+ , reference :: Int
+ } deriving (Show, Eq)
+
+suspicious_dates :: (Int, Int)
+suspicious_dates = (3, 75) -- Difference in years and days that will be marked suspicious (exponential)
+
+type QualityFloat = Quality Float
+
+
+
+checkEntity :: Config -> Map Int Entity -> LegalEntity -> [Score]
+checkEntity config entities' entity = findMatchingEntities config entity $ toList entities'
+
+findMatchingEntities :: Config -> LegalEntity -> [(Int, Entity)] -> [Score]
+findMatchingEntities _ _ [] = []
+findMatchingEntities config entity ((ssid,ent):ents) =
+ let
+ points = compareEntity config entity ent
+ max_points = foldl1 (+) [ if toList (entity_addresses ent) == [] then 0 else weight_address config
+ , if toList (entity_names ent) == [] then 0 else weight_name config
+ ]
+ in
+ if points >= threshold_points config || points / max_points >= threshold_confidence config
+ then let
+ score = Score { match_quality = if points >= perfect_points config then 1 else points / perfect_points config
+ , confidence = points / max_points
+ , expiration = 0
+ , reference = ssid
+ }
+ in
+ score:findMatchingEntities config entity ents
+ else findMatchingEntities config entity ents
+
+compareEntity :: Config -> LegalEntity -> Entity -> Float
+compareEntity config legal_entity entity =
+ foldl1 (+) [ multFloats (weight_address config) address_score (removeQuality . removeSSID)
+ , multFloats (weight_name config) name_score (removeQuality . removeSSID)
+ -- TODO: add additional information to score (phone, email, ...)
+ -- , multFloats 300 info_score removeSSID
+ ]
+ where address_score = checkAddress config (entity_addresses entity) (address legal_entity)
+ name_score = checkNames config (entity_names entity) (company_name legal_entity)
+ -- info_score = ...
+
+
+
+checkPersons :: Config -> Map Int Individual -> NaturalPerson -> [Score]
+checkPersons config individuals' person = checkPersons' config person $ toList individuals'
+
+checkPersons' :: Config -> NaturalPerson -> [(Int, Individual)] -> [Score]
+checkPersons' _ _ [] = []
+checkPersons' config person ((ssid,ind):inds) =
+ let
+ points = checkPerson config person ind
+ max_points = foldl1 (+) [ if toList (addresses ind) == [] then 0 else weight_address config
+ , if toList (birth_dates ind) == [] then 0 else weight_date config
+ , if toList (ids ind) == [] then 0 else weight_id config
+ , if toList (names ind) == [] then 0 else weight_name config
+ , if toList (nationalities ind) == [] then 0 else weight_nationality config
+ ]
+ in
+ if points >= threshold_points config || points / max_points >= threshold_confidence config
+ then let
+ score = Score { match_quality = if points >= perfect_points config then 1 else points / perfect_points config
+ , confidence = points / max_points
+ , expiration = 0
+ , reference = ssid
+ }
+ in
+ score:checkPersons' config person inds
+ else checkPersons' config person inds
+
+checkPerson :: Config -> NaturalPerson -> Individual -> Float
+checkPerson config person individual = foldl1 (+) [ address_points
+ , multFloats 200 id_score removeSSID
+ , multFloats 100 date_score (removeQuality . removeSSID)
+ , 50 * nationality_score
+ , name_points
+ ]
+ where address_score = checkAddress config (addresses individual) (residential person)
+ id_score = checkID config (ids individual) (national_id person)
+ nationality_score = checkCountryCode config (nationalities individual) (nationality person)
+ name_score = checkNames config (names individual) (full_name person)
+ date_score = if name_points == 0
+ then []
+ else checkBirthDate config (birth_dates individual) (birthdate person)
+ address_points = multFloats 150 address_score (removeQuality . removeSSID)
+ name_points = if address_points >= 100
+ then 125
+ else multFloats 125 name_score (removeQuality . removeSSID)
+
+multFloats :: Float -> [a] -> (a -> Float) -> Float
+multFloats factor list toFloat = factor * foldl (\n x -> max n $ toFloat x) 0 list
+
+
+
+checkBirthDate :: Config -> Map Int (Quality (Year, Maybe DayOfYear)) -> Day' -> [WithSSID QualityFloat]
+checkBirthDate config dates (Day' date) = catMaybes $ map compareDate $ toList dates
+ where compareDate (ssid, quality) = let
+ ratio = case removeQuality quality of
+ (year, Just day_of_year) -> compareFullDate config year day_of_year date
+ (year, Nothing) -> compareYear config year date
+ in
+ if ratio >= threshold_ratio config
+ then Just $ WithSSID ssid $ liftQuality (\_ -> ratio) quality
+ else Nothing
+
+compareFullDate :: Config -> Year -> DayOfYear -> Day -> Float
+compareFullDate config year day_of_year day = max ratio_text ratio_date
+ where day' = fromOrdinalDate year day_of_year
+ day_to_text d = pack $ showGregorian d
+ threshold = threshold_ratio config
+ ratio_text = let
+ ratio = ratioToFloat $ damerauLevenshteinNorm (day_to_text day) (day_to_text day')
+ in
+ if ratio >= threshold then ratio else 0
+
+ (year', day_of_year') = toOrdinalDate day
+ (sus_years, sus_days) = suspicious_dates
+
+ ratio_days = threshold**((fromIntegral $ abs $ day_of_year - day_of_year') / fromIntegral sus_days)
+ ratio_years = threshold**((fromIntegral $ abs $ year - year') / fromIntegral sus_years)
+ ratio_date = let
+ ratio = ratio_days * ratio_years
+ in
+ if ratio >= threshold then ratio else 0
+
+compareYear :: Config -> Year -> Day -> Float
+compareYear config year day = if ratio >= threshold then ratio else 0
+ where (year', _) = toOrdinalDate day
+ (sus_years, _) = suspicious_dates
+ threshold = threshold_ratio config
+ ratio = threshold**((fromIntegral $ abs $ year - year') / fromIntegral sus_years)
+
+
+
+checkNames :: Config -> Map Int (Quality [Text]) -> Text -> [WithSSID QualityFloat]
+checkNames config names' name = catMaybes $ map compareName $ toList names'
+ where compareName (ssid, quality) = let
+ ratio = ratioToFloat $ compareText name 0 (removeQuality quality)
+ in
+ if ratio >= threshold_ratio config
+ then Just $ WithSSID ssid $ liftQuality (\_ -> ratio) quality
+ else Nothing
+
+
+
+checkCountryCode :: Config -> Map Int CountryCode -> CountryCode -> Float
+checkCountryCode _ countries country' = if foldl (\b (_,c) -> c == country' || b) False $ toList countries then 1 else 0
+
+
+checkID :: Config -> Map Int Text -> Text -> [WithSSID Float]
+checkID config ids' id' = catMaybes $ map compareID $ toList ids'
+ where compareID (ssid, id'') = let
+ ratio = ratioToFloat $ compareText id' 0 [id'']
+ in
+ if ratio >= (threshold_ratio config + 1) / 2
+ then Just $ WithSSID ssid ratio
+ else Nothing
+
+
+checkAddress :: Config -> Map Int (Quality SSL.Address) -> GLS.Address -> [WithSSID QualityFloat]
+checkAddress config addresses' address' = catMaybes $ map (compareAddress config address') $ toList addresses'
+
+compareAddress :: Config -> GLS.Address -> (Int, Quality SSL.Address) -> Maybe (WithSSID QualityFloat)
+compareAddress config gls_address (ssid, quality) = if country_score >= 0.75
+ then Just $ WithSSID ssid $ liftQuality (\_ -> country_score) quality
+ else Nothing
+ where ssl_address = removeQuality quality
+ total_score = totalFromMaybes [ details_score
+ , area_score
+ , location_score
+ , zip_code_score
+ ]
+ country_score = case SSL.country ssl_address of
+ Just c -> if c == GLS.country gls_address then 0.5 * (total_score + 1) else 0
+ Nothing -> total_score
+ details_score = case details ssl_address of
+ Just det -> let
+ possible_numbers = catMaybes [ Just $ street_number gls_address
+ , building_number gls_address
+ , lines gls_address
+ ]
+ possible_info = catMaybes [ Just $ street_name gls_address
+ , building_name gls_address
+ , country_subdivision gls_address
+ , town_district gls_address
+ , town_location gls_address
+ , Just $ zipcode gls_address
+ ]
+ possible_details = possible_numbers ++ possible_info
+ perms = permutateText possible_details
+ clean_details = cleanText det
+ ratio = ratioToFloat $ compareTexts clean_details 0 perms
+ perfect_matches = foldl (\c i -> if foldl (\b d -> b || i `T.isInfixOf` d) False clean_details then c + 1 else c) 0 possible_info
+ in
+ Just $ if ratio >= threshold_ratio config
+ then ratio
+ else if perfect_matches >= 3 then perfect_matches * 0.2 else if perfect_matches > 1 then 0.5 else 0
+ Nothing -> Nothing
+ area_score = case area ssl_address of
+ Just areas -> let
+ perms = permutateText $ catMaybes [ town_location gls_address
+ , town_district gls_address
+ , country_subdivision gls_address
+ ]
+ ratio = ratioToFloat $ compareTexts areas 0 perms
+ in
+ if ratio >= threshold_ratio config then Just ratio else Nothing
+ Nothing -> Nothing
+ location_score = case location ssl_address of
+ Just lcs -> let
+ perms = permutateText $ catMaybes [ town_location gls_address
+ , town_district gls_address
+ , country_subdivision gls_address
+ ]
+ ratio = ratioToFloat $ compareTexts lcs 0 perms
+ in
+ if ratio >= threshold_ratio config then Just ratio else Nothing
+ Nothing -> Nothing
+ zip_code_score = case zip_code ssl_address of
+ Just zc -> let
+ ratio = ratioToFloat $ compareText zc 0 [zipcode gls_address]
+ in
+ if ratio >= threshold_ratio config then Just ratio else Nothing
+ Nothing -> Nothing
+
+
+cleanText :: [Text] -> [Text]
+cleanText text = map (T.foldl (\new_text char -> if char `elem` chars_to_rm
+ then new_text
+ else snoc new_text char
+ ) start_text) text
+ where chars_to_rm = ".,-" :: String
+ start_text = "" :: Text
+
+permutateText :: [Text] -> [Text]
+permutateText elems = map (intercalate " ") $ concatMap permutations $ subsequences elems
+
+totalFromMaybes :: [Maybe Float] -> Float
+totalFromMaybes floats = let
+ list = catMaybes floats
+ elems = length list
+ total = foldl (+) 0 list
+ in
+ if elems == 0 then 0 else total / fromIntegral elems
+
+ratioToFloat :: Ratio Int -> Float
+ratioToFloat r = (fromIntegral . numerator) r / (fromIntegral . denominator) r
+
+compareTexts :: [Text] -> Ratio Int -> [Text] -> Ratio Int
+compareTexts _ ratio [] = ratio
+compareTexts texts ratio (t:ts) = let
+ new_ratio = compareText t ratio texts
+ in
+ if new_ratio > ratio
+ then compareTexts texts new_ratio ts
+ else compareTexts texts ratio ts
+
+compareText :: Text -> Ratio Int -> [Text] -> Ratio Int
+compareText _ ratio [] = ratio
+compareText text ratio (t:ts) = let
+ new_ratio = damerauLevenshteinNorm text t
+ in
+ if new_ratio > ratio
+ then compareText text new_ratio ts
+ else compareText text ratio ts
diff --git a/src/Robocop/Config.hs b/src/Robocop/Config.hs
@@ -0,0 +1,228 @@
+-- SPDX-FileCopyrightText: 2025 LNRS
+--
+-- SPDX-License-Identifier: AGPL-3.0-or-later
+-- SPDX-License-Identifier: EUPL-1.2
+
+{-# LANGUAGE DeriveGeneric #-}
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE LambdaCase #-}
+
+module Robocop.Config
+ ( inputToConfig
+ , checkConfig
+ , configCodec
+ , opts
+ ) where
+
+import Robocop.Error
+import Robocop.Type
+
+import Control.Monad
+
+import qualified Data.Text as T
+
+import Options.Applicative
+
+import System.Directory
+import System.FilePath
+
+import Toml as Toml hiding (bool)
+
+inputToConfig :: Config -> CommandLine -> Config
+inputToConfig toml cl =
+ Config { verbosity = case cl_verbosity cl of Just v -> v; Nothing -> verbosity toml
+ , ssl_location = case cl_ssl_location cl of Just l -> l; Nothing -> ssl_location toml
+ , threshold_ratio = case cl_threshold_ratio cl of Just p -> p; Nothing -> threshold_ratio toml
+ , threshold_points = case cl_threshold_points cl of Just p -> p; Nothing -> threshold_points toml
+ , threshold_confidence = case cl_threshold_confidence cl of Just p -> p; Nothing -> threshold_confidence toml
+ , perfect_points = case cl_perfect_points cl of Just p -> p; Nothing -> perfect_points toml
+ , weight_address = case cl_weight_address cl of Just p -> p; Nothing -> weight_address toml
+ , weight_date = case cl_weight_date cl of Just p -> p; Nothing -> weight_date toml
+ , weight_id = case cl_weight_id cl of Just p -> p; Nothing -> weight_id toml
+ , weight_name = case cl_weight_name cl of Just p -> p; Nothing -> weight_name toml
+ , weight_nationality = case cl_weight_nationality cl of Just p -> p; Nothing -> weight_nationality toml
+ }
+
+checkConfig :: Config -> IO Bool
+checkConfig config = do
+ valid_ssl <- checkSSL config
+ valid_points <- checkPoints config
+
+ let valid = foldl1 (&&) [ valid_ssl
+ , valid_points
+ ]
+ return valid
+
+checkSSL :: Config -> IO Bool
+checkSSL config = do
+ let fp = ssl_location config
+ let v = verbosity config
+
+ bool <- do exists <- doesFileExist fp
+ when (not exists) $ do curr_dir <- getCurrentDirectory
+ (handleError v . Left) $ Robocop_NotFound (T.pack $ curr_dir </> fp) ".xml file containing sanctions"
+ -- TODO: implement RelaxNG validation
+ return exists
+
+ return bool
+
+checkPoints :: Config -> IO Bool
+checkPoints config = do
+ let v = verbosity config
+
+ bool <- do let total = foldl1 (+) [ weight_address config
+ , weight_date config
+ , weight_id config
+ , weight_name config
+ , weight_nationality config
+ ]
+ threshold = threshold_points config
+ when (total < threshold)
+ $ do (handleError v . Left)
+ $ Robocop_InvalidDistribution
+ $ T.pack ("Total points obtainable (" ++ show total ++ ") lower than threshold (" ++ show threshold ++ ")")
+ when (threshold_ratio config < 0 || threshold_ratio config > 1)
+ $ do (handleError v . Left) $ Robocop_InvalidDistribution "Threshold ratio should be between 0 and 1"
+ when (threshold_confidence config < 0 || threshold_confidence config > 1)
+ $ do (handleError v . Left) $ Robocop_InvalidDistribution "Threshold confidence should be between 0 and 1"
+ when (threshold_points config < 0)
+ $ do (handleError v . Left) $ Robocop_InvalidDistribution "Threshold points should be positive"
+ when (perfect_points config < 0)
+ $ do (handleError v . Left) $ Robocop_InvalidDistribution "Perfect points should be positive"
+ when (weight_address config < 0)
+ $ do (handleError v . Left) $ Robocop_InvalidDistribution "Address weight should be positive"
+ when (weight_date config < 0)
+ $ do (handleError v . Left) $ Robocop_InvalidDistribution "Birthdate weight should be positive"
+ when (weight_id config < 0)
+ $ do (handleError v . Left) $ Robocop_InvalidDistribution "Identification document weight should be positive"
+ when (weight_name config < 0)
+ $ do (handleError v . Left) $ Robocop_InvalidDistribution "Name weight should be positive"
+ when (weight_nationality config < 0)
+ $ do (handleError v . Left) $ Robocop_InvalidDistribution "Nationality weight should be positive"
+ return (total >= threshold)
+ return bool
+
+
+
+-- | Toml config parsing
+configCodec :: TomlCodec Config
+configCodec = Config
+ <$> verbosityCodec "verbosity" .= verbosity
+ <*> Toml.string "ssl_location" .= ssl_location
+ <*> Toml.float "threshold_ratio" .= threshold_ratio
+ <*> Toml.float "threshold_points" .= threshold_points
+ <*> Toml.float "threshold_confidence" .= threshold_confidence
+ <*> Toml.float "perfect_points" .= perfect_points
+ <*> Toml.float "weight_address" .= weight_address
+ <*> Toml.float "weight_date" .= weight_date
+ <*> Toml.float "weight_id" .= weight_id
+ <*> Toml.float "weight_name" .= weight_name
+ <*> Toml.float "weight_nationality" .= weight_nationality
+
+verbosityCodec :: Key -> TomlCodec Verbosity
+verbosityCodec = textBy showVerbosity parseVerbosity
+
+showVerbosity :: Verbosity -> T.Text
+showVerbosity v = case v of
+ Test -> "Test"
+ Silent -> "Silent"
+ Info -> "Info"
+ Errors -> "Errors"
+ Debug -> "Debug"
+
+parseVerbosity :: T.Text -> Either T.Text Verbosity
+parseVerbosity txt = case txt of
+ "Test" -> Right Test
+ "Silent" -> Right Silent
+ "Info" -> Right Info
+ "Errors" -> Right Errors
+ "Debug" -> Right Debug
+ other -> Left $ "Invalid verbosity: " <> other
+
+
+
+
+-- | Custom commandline flag for verbosity-level Silent: --silent
+verbositySilent :: Parser Verbosity
+verbositySilent = flag' Silent
+ ( long "silent"
+ <> help "Print nothing to commandline unless an error occurs" )
+
+-- | Custom commandline flag for verbosity-level Info: --info
+verbosityInfo :: Parser Verbosity
+verbosityInfo = flag' Info
+ ( long "info"
+ <> help "Only print information about the process to commandline" )
+
+-- | Custom commandline flag for verbosity-level Errors: --errors
+verbosityErrors :: Parser Verbosity
+verbosityErrors = flag' Errors
+ ( long "errors"
+ <> help "Print all error messages to commandline" )
+
+-- | Custom commandline flag for verbosity-level Debug: --debug
+verbosityDebug :: Parser Verbosity
+verbosityDebug = flag' Debug
+ ( long "debug"
+ <> help "Print all available information to commandline" )
+
+-- | Custom commandline parser for Verbosity type
+verbosityParser :: Parser Verbosity
+verbosityParser = verbositySilent <|> verbosityInfo <|> verbosityErrors <|> verbosityDebug
+
+-- | Custom commandline parser for CommandLine type
+commandLine :: Parser CommandLine
+commandLine = CommandLine
+ <$> optional verbosityParser
+ <*> strOption
+ ( long "config"
+ <> metavar "FILENAME"
+ <> help "Location of config file"
+ <> value "robocop.conf" )
+ <*> optional ( strOption
+ ( long "input"
+ <> metavar "FILENAME"
+ <> help "Location of Swiss Sanction List" ) )
+ <*> optional ( option auto
+ ( long "threshold-ratio"
+ <> metavar "Float"
+ <> help "Ratio between 0-1" ) )
+ <*> optional ( option auto
+ ( long "threshold-points"
+ <> metavar "Integer"
+ <> help "Points needed to flag entry as match" ) )
+ <*> optional ( option auto
+ ( long "threshold-confidence"
+ <> metavar "Float"
+ <> help "Minimum confidence level between 0-1" ) )
+ <*> optional ( option auto
+ ( long "perfect-points"
+ <> metavar "Integer"
+ <> help "Amount of points required to get a 100% confidence result" ) )
+ <*> optional ( option auto
+ ( long "address-weight"
+ <> metavar "Integer"
+ <> help "Points given to a 100% address match" ) )
+ <*> optional ( option auto
+ ( long "date-weight"
+ <> metavar "Integer"
+ <> help "Points given to a 100% birthdate match" ) )
+ <*> optional ( option auto
+ ( long "id-weight"
+ <> metavar "Integer"
+ <> help "Points given to a 100% identification document match" ) )
+ <*> optional ( option auto
+ ( long "name-weight"
+ <> metavar "Integer"
+ <> help "Points given to a 100% name match" ) )
+ <*> optional ( option auto
+ ( long "nationality-weight"
+ <> metavar "Integer"
+ <> help "Points given to a 100% nationality match" ) )
+
+-- | Information about CommandLine parser
+opts :: ParserInfo CommandLine
+opts = info (commandLine <**> helper)
+ ( fullDesc
+ <> progDesc "Match customers to Swiss Sanction List"
+ <> header "Robocop by LNRS" )
diff --git a/src/Robocop/Error.hs b/src/Robocop/Error.hs
@@ -0,0 +1,88 @@
+-- SPDX-FileCopyrightText: 2025 LNRS
+--
+-- SPDX-License-Identifier: AGPL-3.0-or-later
+-- SPDX-License-Identifier: EUPL-1.2
+
+{-# LANGUAGE DeriveDataTypeable #-}
+{-# LANGUAGE DeriveGeneric #-}
+{-# LANGUAGE OverloadedStrings #-}
+
+module Robocop.Error
+ ( Robocop_Error(..)
+ , renderError
+ , handleError
+ , showError
+ ) where
+
+import Robocop.Type
+
+import Control.Exception (Exception, SomeException)
+import Control.Monad (when)
+import Data.Text (Text)
+import Data.Typeable (Typeable)
+import GHC.Generics (Generic)
+import System.Exit (ExitCode (..), exitWith)
+import System.IO hiding (hPutStrLn)
+
+import qualified Data.Text as T (pack)
+import qualified Data.Text.IO as TIO
+
+-- | Custom type to express exceptions in DMARC.* that cause errors
+data Robocop_Error = Robocop_InvalidDistribution Text
+ | Robocop_InvalidRelaxNG Text
+ | Robocop_InvalidXML Text String
+ | Robocop_NotFound Text Text
+ | Robocop_NotImplemented Text
+ | Robocop_XMLParsingError Text SomeException
+ deriving (Show, Typeable, Generic)
+
+instance Exception Robocop_Error
+
+renderError :: Robocop_Error -> Text
+renderError e =
+ case e of
+ Robocop_InvalidDistribution msg -> "Error: " <> msg
+ Robocop_InvalidRelaxNG fp -> "Error: " <> fp <> " is not a valid RelaxNG-schema"
+ Robocop_InvalidXML fp err' -> "Error: " <> fp <> " is not valid for RelaxNG-schema\n" <> tshow err'
+ Robocop_NotImplemented msg -> "Error: " <> msg <> " has not been implemented yet, please change your configuration file"
+ Robocop_NotFound fp desc -> "Error: could not find " <> fp <> " (" <> desc <> ")"
+ Robocop_XMLParsingError dat err' -> "Error: could not parse " <> dat <> "\n" <> tshow err'
+
+handleError :: Verbosity -> Either Robocop_Error a -> IO a
+handleError _ (Right r) = return r
+handleError v (Left e) =
+ case e of
+ _ -> err v exit_code (renderError e)
+ where
+ exit_code =
+ case e of
+ Robocop_InvalidDistribution{} -> 1
+ Robocop_InvalidRelaxNG{} -> 2
+ Robocop_InvalidXML{} -> 3
+ Robocop_NotImplemented{} -> 4
+ Robocop_NotFound{} -> 5
+ Robocop_XMLParsingError{} -> 6
+
+-- | Function to show helpfull error/warning message
+showError :: Robocop_Error -> IO ()
+showError e = hPutStrLn stderr (renderError e)
+
+-- | Function to exit program with specific exit code and msg
+err :: Verbosity -> Int -> Text -> IO a
+err v exit_code msg = do
+ when (v /= Test) $ hPutStrLn stderr msg
+ _ <- exitWith $ ExitFailure exit_code
+ return undefined
+
+-- | Convert any Showable type to T.Text
+tshow :: Show a => a -> Text
+tshow = T.pack . show
+
+-- | Print T.Text nicely to commandline
+hPutStrLnWith :: Newline -> Handle -> Text -> IO ()
+hPutStrLnWith eol h s =
+ hSetNewlineMode h (NewlineMode eol eol) >>
+ hSetEncoding h utf8 >> TIO.hPutStrLn h s
+
+hPutStrLn :: Handle -> Text -> IO ()
+hPutStrLn = hPutStrLnWith nativeNewline
diff --git a/src/Robocop/GLS/Type.hs b/src/Robocop/GLS/Type.hs
@@ -0,0 +1,136 @@
+-- SPDX-FileCopyrightText: 2025 LNRS
+--
+-- SPDX-License-Identifier: AGPL-3.0-or-later
+-- SPDX-License-Identifier: EUPL-1.2
+
+-- | See https://git.taler.net/gana.git/tree/gnu-taler-form-attributes/registry.rec
+
+{-# LANGUAGE DeriveGeneric #-}
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE PatternSynonyms #-}
+{-# LANGUAGE ViewPatterns #-}
+{-# OPTIONS_GHC -Wno-orphans #-}
+
+module Robocop.GLS.Type
+ ( Address(..)
+ , Entry(..)
+ , LegalEntity(..)
+ , NaturalPerson(..)
+ , pattern YMD
+ ) where
+
+import Control.Applicative ((<|>))
+
+import Data.Aeson (FromJSON(..), ToJSON(..), (.:), (.:?), Value(..))
+import Data.ISO3166_CountryCodes hiding (NP)
+import Data.Text
+
+import GHC.Generics
+
+import Robocop.Type
+
+data Entry = NP NaturalPerson
+ | LE LegalEntity deriving (Show, Generic, Eq)
+ -- | F
+
+data NaturalPerson = NaturalPerson
+ { full_name :: Text
+ , last_name :: Text
+ , residential :: Address
+-- , phone :: Maybe Text
+-- , email :: Maybe Text
+ , birthdate :: Day' -- parseTimeM False defaultTimeLocale "%Y-%-m-%-d" YYYY-MM-DD
+ , nationality :: CountryCode -- 2-letter ISO country-code
+ , national_id :: Text
+-- , national_id_copy :: FilePath
+-- , company_name :: Maybe Text
+-- , registered_office :: Maybe Text
+-- , company_id :: Maybe Text
+-- , company_id_copy :: Maybe FilePath
+ } deriving (Show, Eq, Generic)
+
+data Address = Address
+ { country :: CountryCode -- 2-letter ISO country-code
+ , street_name :: Text
+ , street_number :: Text
+ , lines :: Maybe Text -- Additional address information
+ , building_name :: Maybe Text
+ , building_number :: Maybe Text
+ , zipcode :: Text
+ , town_location :: Maybe Text
+ , town_district :: Maybe Text
+ , country_subdivision :: Maybe Text
+ } deriving (Show, Eq, Generic)
+
+data LegalEntity = LegalEntity
+ { company_name :: Text
+ , address :: Address
+ , contact_person_name :: Maybe Text
+ , phone :: Maybe Text
+ , email :: Maybe Text
+ , id :: Text
+-- , id_copy :: FilePath
+ } deriving (Show, Eq, Generic)
+
+instance FromJSON Entry where
+ parseJSON e =
+ (NP <$> parseJSON e)
+ <|> (LE <$> parseJSON e)
+instance FromJSON NaturalPerson where
+ parseJSON (Object p) = NaturalPerson
+ <$> p .: "full_name"
+ <*> p .: "last_name"
+ <*> p .: "address"
+ <*> p .: "birthdate"
+ <*> p .: "nationality"
+ <*> p .: "national_id"
+ parseJSON _ = fail "Expected a natural person object"
+instance FromJSON Address where
+ parseJSON (Object a) = Address
+ <$> a .: "country"
+ <*> a .: "street_name"
+ <*> a .: "street_number"
+ <*> a .:? "lines"
+ <*> a .:? "building_name"
+ <*> a .:? "building_number"
+ <*> a .: "zipcode"
+ <*> a .:? "town_location"
+ <*> a .:? "town_district"
+ <*> a .:? "country_subdivision"
+ parseJSON _ = fail "Expected an address object"
+instance FromJSON LegalEntity where
+ parseJSON (Object e) = LegalEntity
+ <$> e .: "company_name"
+ <*> e .: "address"
+ <*> e .:? "contact_person_name"
+ <*> e .:? "phone"
+ <*> e .:? "email"
+ <*> e .: "id"
+ parseJSON _ = fail "Expected a legal entity object"
+instance FromJSON CountryCode where
+ parseJSON (String t) = pure (read $ unpack t)
+ parseJSON _ = fail "Expected ISO3166 compliant country code"
+
+
+instance ToJSON Entry
+instance ToJSON NaturalPerson
+instance ToJSON Address
+instance ToJSON LegalEntity
+instance ToJSON CountryCode where
+ toJSON = toJSON . show
+
+-- data Founder = Founder
+-- { full_name :: Text
+-- , residential_address :: ResidentialAddress
+-- , birthdate :: AbsoluteDate
+-- , nationality :: CountryCode
+-- , authorization_type :: Text
+-- , national_id :: Text
+-- , national_copy :: FilePath
+-- , power_of_attorney :: Maybe Powers
+-- , power_of_attorney_other :: Maybe Text
+-- } deriving (Show, Eq)
+
+data Powers = CR
+ | MANDATE
+ | OTHER deriving (Show, Eq)
diff --git a/src/Robocop/SSL.hs b/src/Robocop/SSL.hs
@@ -0,0 +1,14 @@
+-- SPDX-FileCopyrightText: 2025 LNRS
+--
+-- SPDX-License-Identifier: AGPL-3.0-or-later
+-- SPDX-License-Identifier: EUPL-1.2
+
+module Robocop.SSL
+ ( module Robocop.SSL.Match
+ , module Robocop.SSL.Type
+ , parseSwissSanctionsList
+ ) where
+
+import Robocop.SSL.Match
+import Robocop.SSL.Type
+import Robocop.SSL.XML.Parse (parseSwissSanctionsList)
diff --git a/src/Robocop/SSL/Match.hs b/src/Robocop/SSL/Match.hs
@@ -0,0 +1,162 @@
+-- SPDX-FileCopyrightText: 2025 LNRS
+--
+-- SPDX-License-Identifier: AGPL-3.0-or-later
+-- SPDX-License-Identifier: EUPL-1.2
+
+{-# LANGUAGE OverloadedStrings #-}
+
+module Robocop.SSL.Match
+ ( xmlToSSL
+ ) where
+
+import Prelude hiding (lookup)
+
+import Control.Monad (liftM2)
+
+import Data.ISO3166_CountryCodes
+import Data.List (sortOn, permutations, subsequences)
+import Data.Map (insert, Map, lookup, empty)
+import Data.Maybe
+import Data.Time.Format
+import Data.Time.Calendar (fromGregorian)
+import Data.Time.Calendar.OrdinalDate
+
+import qualified Data.Text as T
+
+import Robocop.Type
+import Robocop.SSL.Type as SSL
+
+import Robocop.SSL.XML.Type as XML
+import qualified Robocop.SSL.XML.Entity.Type as Ent
+import qualified Robocop.SSL.XML.Individual.Type as Ind
+-- import qualified KYC.SSL.XML.Object.Type as Obj
+
+import Text.Read (readMaybe)
+
+xmlToSSL :: SwissSanctionsList -> Targets
+xmlToSSL xml = let
+ targets' = map (\(WithSSID _ t) -> target_type t) (targets xml)
+ entities' = mapMaybe (\t -> case t of Ent ent -> Just ent; _ -> Nothing) targets'
+ individuals' = mapMaybe (\t -> case t of Ind ind -> Just ind; _ -> Nothing) targets'
+ -- objects' = mapMaybe (\t -> case t of Obj obj -> Just obj; _ -> Nothing) targets'
+ places' = foldl (\ps (WithSSID ssid p) -> insert ssid p ps) empty (XML.places xml)
+ in
+ Targets { start_date = parseTimeM True defaultTimeLocale "%Y-%-m-%-d" $ T.unpack $ date xml
+ , entities = foldl (insertEntity places') empty entities'
+ , individuals = foldl (insertIndividual places') empty individuals'
+ }
+
+insertEntity :: Map Int XML.Place -> Map Int SSL.Entity -> WithSSID Ent.Entity -> Map Int SSL.Entity
+insertEntity places' map' (WithSSID ssid entity) = insert ssid ssl_entity map'
+ where ssl_entity = SSL.Entity { entity_addresses = ssl_addresses
+ , entity_dates = ssl_dates
+ , entity_names = ssl_names
+ , SSL.other_info = ssl_info
+ }
+ ssl_addresses = case Ent.addresses entity of
+ Just addr -> foldl (insertAddress places') empty addr
+ Nothing -> empty
+ ssl_dates = case Ent.dates entity of
+ Just ds -> foldl (insertFuncWithSSID $ liftQuality dateToOrdinal) empty ds
+ Nothing -> empty
+ ssl_names = foldl (insertFuncWithSSID permutateNames) empty (Ent.names entity)
+ ssl_info = case Ent.other_info entity of
+ Just info -> foldl insertWithSSID empty info
+ Nothing -> empty
+
+insertIndividual :: Map Int XML.Place -> Map Int SSL.Individual -> WithSSID Ind.Individual -> Map Int SSL.Individual
+insertIndividual places' map' (WithSSID ssid individual) = insert ssid ssl_individual map'
+ where ssl_individual = SSL.Individual { addresses = ssl_addresses
+ , birth_dates = ssl_birth_dates
+ , ids = ssl_ids
+ , names = ssl_names
+ , nationalities = ssl_nationalities
+ }
+
+ ssl_addresses = case Ind.addresses individual of
+ Just addr -> foldl (insertAddress places') empty addr
+ Nothing -> empty
+
+ ssl_birth_dates = case Ind.birth_dates individual of
+ Just bds -> foldl (insertFuncWithSSID $ liftQuality dateToOrdinal) empty bds
+ Nothing -> empty
+
+ ssl_ids = case Ind.ids individual of
+ Just ids' -> foldl (insertFuncWithSSID id_number) empty ids'
+ Nothing -> empty
+
+ ssl_names = foldl (insertFuncWithSSID permutateNames) empty (Ind.names individual)
+
+ ssl_nationalities = case Ind.nationalities individual of
+ Just nat -> foldl (insertMaybeFuncWithSSID (readMaybe . T.unpack . country_code)) empty nat :: Map Int CountryCode
+ Nothing -> empty
+
+insertMaybeFuncWithSSID :: (a -> Maybe b) -> Map Int b -> WithSSID a -> Map Int b
+insertMaybeFuncWithSSID func map' (WithSSID ssid x) = case func x of
+ Just y -> insert ssid y map'
+ Nothing -> map'
+
+insertFuncWithSSID :: (a -> b) -> Map Int b -> WithSSID a -> Map Int b
+insertFuncWithSSID func map' (WithSSID ssid x) = insert ssid (func x) map'
+
+insertWithSSID :: Map Int a -> WithSSID a -> Map Int a
+insertWithSSID map' (WithSSID ssid x) = insert ssid x map'
+
+
+
+insertAddress :: Map Int XML.Place -> Map Int (Quality SSL.Address) -> WithSSID (Quality XML.Address) -> Map Int (Quality SSL.Address)
+insertAddress places' map' (WithSSID ssid qual) = insert ssid gls_quality map'
+ where ssl_address = removeQuality qual
+ gls_quality = liftQuality (\_ -> gls_address) qual
+ gls_address = SSL.Address { SSL.area = area'
+ , SSL.country = country'
+ , SSL.details = details'
+ , SSL.location = location'
+ , SSL.zip_code = XML.zip_code ssl_address
+ }
+
+ details' = case (XML.details ssl_address, XML.remark ssl_address) of
+ (Just d, Just r) -> Just [d, r]
+ (Just d, _ ) -> Just [d]
+ (_ , Just r) -> Just [r]
+ _ -> Nothing
+
+ (area', country', location') =
+ case lookup (place_id ssl_address) places' of
+ Just place -> let
+ gls_area = case (XML.area place, area_variant place) of
+ (Just a, Just av) -> Just $ a:(maybeToList $ getVariant av)
+ (Just a, _ ) -> Just [a]
+ (_, Just av) -> case getVariant av of
+ Just v -> Just [v]
+ Nothing -> Nothing
+ _ -> Nothing
+ gls_country = case XML.country place of
+ Just c -> (readMaybe . T.unpack . country_code) c :: Maybe CountryCode
+ Nothing -> Nothing
+ gls_location = case (XML.location place, location_variant place) of
+ (Just l, Just lv) -> Just $ l:(maybeToList $ getVariant lv)
+ (Just l, _ ) -> Just [l]
+ (_ , Just lv) -> case getVariant lv of
+ Just v -> Just [v]
+ Nothing -> Nothing
+ _ -> Nothing
+ in
+ (gls_area, gls_country, gls_location)
+ Nothing -> (Nothing, Nothing, Nothing)
+
+
+dateToOrdinal :: Date -> (Year, Maybe DayOfYear)
+dateToOrdinal date' = case (month date', day date') of
+ (Just m, Just d) -> let (y, doy) = toOrd m d in (y, Just doy)
+ _ -> (year', Nothing)
+ where year' = toEnum $ year date'
+ toOrd month' day' = toOrdinalDate $ fromGregorian year' month' day'
+
+
+-- All possible name combinations, including variants, in right order
+-- FUTURE IDEA: check all name-parts seperately for similarity and add their score, probably need to add a similarity check between the name-parts to make sure they dont trigger on the same characters
+permutateNames :: Quality Name -> Quality [T.Text]
+permutateNames quality = liftQuality all_permutations quality
+ where all_permutations n = map (T.intercalate " ") $ all_combinations $ [ name np : map variant (variants np) | np <- sortOn order (name_parts n) ]
+ all_combinations ns = concatMap permutations $ concatMap subsequences $ foldr (liftM2 (:)) [[]] ns
diff --git a/src/Robocop/SSL/Type.hs b/src/Robocop/SSL/Type.hs
@@ -0,0 +1,48 @@
+-- SPDX-FileCopyrightText: 2025 LNRS
+--
+-- SPDX-License-Identifier: AGPL-3.0-or-later
+-- SPDX-License-Identifier: EUPL-1.2
+
+module Robocop.SSL.Type
+ ( Address(..)
+ , Entity(..)
+ , Individual(..)
+ , Targets(..)
+ ) where
+
+import Data.ISO3166_CountryCodes
+import Data.Map
+import Data.Text
+import Data.Time.Calendar.OrdinalDate
+
+import Robocop.Type
+
+data Targets = Targets
+ { start_date :: Maybe Day
+ , individuals :: Map Int Individual
+ , entities :: Map Int Entity
+-- , objects :: Map Int UpdatedObject
+ } deriving (Show, Eq)
+
+data Individual = Individual
+ { addresses :: Map Int (Quality Address) -- Map (key = SSID) (elem = relevant address info)
+ , birth_dates :: Map Int (Quality (Year, Maybe DayOfYear)) -- Map (key = SSID) (elem = date)
+ , ids :: Map Int Text -- Map (key = SSID) (elem = id_number)
+ , names :: Map Int (Quality [Text]) -- Map (key = SSID) (elem = all permutations of name)
+ , nationalities :: Map Int CountryCode -- Map (key = SSID) (elem = ISO country-code)
+ } deriving (Show, Eq)
+
+data Entity = Entity
+ { entity_addresses :: Map Int (Quality Address) -- Map (key = SSID) (elem = relevant address info)
+ , entity_dates :: Map Int (Quality (Year, Maybe DayOfYear))
+ , entity_names :: Map Int (Quality [Text]) -- Map (key = SSID) (elem = all combinations of name)
+ , other_info :: Map Int Text -- Map (key = SSID) (elem = registration number | email | phone)
+ } deriving (Show, Eq)
+
+data Address = Address
+ { country :: Maybe CountryCode -- country -> CountryCode
+ , details :: Maybe [Text] -- street, number (w/ addition), address-details + remark elements
+ , area :: Maybe [Text] -- area (maybe town_location, town_district or country_subdivision)
+ , location :: Maybe [Text] -- location (maybe town_location, town_district or country_subdivision)
+ , zip_code :: Maybe Text
+ } deriving (Show, Eq)
diff --git a/src/Robocop/SSL/XML/Entity/Parse.hs b/src/Robocop/SSL/XML/Entity/Parse.hs
@@ -0,0 +1,60 @@
+-- SPDX-FileCopyrightText: 2025 LNRS
+--
+-- SPDX-License-Identifier: AGPL-3.0-or-later
+-- SPDX-License-Identifier: EUPL-1.2
+
+{-# LANGUAGE Arrows #-}
+{-# LANGUAGE BlockArguments #-}
+{-# LANGUAGE TemplateHaskell #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+
+module Robocop.SSL.XML.Entity.Parse
+ ( getEntity
+ ) where
+
+import Data.Tree.NTree.TypeDefs (NTree)
+
+import Text.XML.HXT.Core hiding (getName)
+
+import Robocop.Type
+import Robocop.SSL.XML.Type
+import Robocop.SSL.XML.Entity.Type
+
+import Robocop.SSL.XML.Helpers.Parse
+
+
+
+getEntity :: IOSLA (XIOState ()) (NTree XNode) TargetType
+getEntity = atElem "entity" >>>
+ proc ent -> do
+ WithSSID ssid identity <- getEntityIdentity -< ent
+
+ justifications' <- getMaybeFunction (listA $ getElemWithSSID "justification" ) -< ent
+ other_info' <- getMaybeFunction (listA $ getElemWithSSID "other-information") -< ent
+ relations' <- getMaybeFunction (listA getRelation) -< ent
+
+ returnA -< Ent $ WithSSID ssid $ Entity
+ { addresses = id_addresses identity
+ , dates = id_dates identity
+ , names = id_names identity
+ , justifications = justifications'
+ , other_info = other_info'
+ , relations = relations'
+ }
+
+
+
+getEntityIdentity :: IOSLA (XIOState ()) (NTree XNode) (WithSSID EntityIdentity)
+getEntityIdentity = atElem "identity" >>>
+ proc id' -> do
+ ssid <- attrToInt "ssid" -< id'
+
+ addresses' <- getMaybeFunction (listA getAddress) -< id'
+ dates' <- getMaybeFunction (listA getDate) -< id'
+ names' <- listA getName -< id'
+
+ returnA -< WithSSID ssid $ EntityIdentity
+ { id_addresses = addresses'
+ , id_dates = dates'
+ , id_names = names'
+ }
diff --git a/src/Robocop/SSL/XML/Entity/Type.hs b/src/Robocop/SSL/XML/Entity/Type.hs
@@ -0,0 +1,31 @@
+-- SPDX-FileCopyrightText: 2025 LNRS
+--
+-- SPDX-License-Identifier: AGPL-3.0-or-later
+-- SPDX-License-Identifier: EUPL-1.2
+
+module Robocop.SSL.XML.Entity.Type
+ ( Entity(..)
+ , EntityIdentity(..)
+ ) where
+
+import Data.Text
+
+import Robocop.Type
+import Robocop.SSL.XML.Helpers.Type
+
+
+
+data Entity = Entity
+ { addresses :: Maybe [WithSSID (Quality Address)]
+ , dates :: Maybe [WithSSID (Quality Date)]
+ , names :: [WithSSID (Quality Name)]
+ , justifications :: Maybe [WithSSID Text]
+ , other_info :: Maybe [WithSSID Text]
+ , relations :: Maybe [WithSSID Relation]
+ } deriving (Show, Eq)
+
+data EntityIdentity = EntityIdentity
+ { id_addresses :: Maybe [WithSSID (Quality Address)]
+ , id_dates :: Maybe [WithSSID (Quality Date)]
+ , id_names :: [WithSSID (Quality Name)]
+ } deriving (Show, Eq)
diff --git a/src/Robocop/SSL/XML/Helpers/Parse.hs b/src/Robocop/SSL/XML/Helpers/Parse.hs
@@ -0,0 +1,244 @@
+-- SPDX-FileCopyrightText: 2025 LNRS
+--
+-- SPDX-License-Identifier: AGPL-3.0-or-later
+-- SPDX-License-Identifier: EUPL-1.2
+
+{-# LANGUAGE Arrows #-}
+{-# LANGUAGE BlockArguments #-}
+{-# LANGUAGE TemplateHaskell #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+
+module Robocop.SSL.XML.Helpers.Parse
+ ( atElem
+ , atElemWithAttr
+
+ , attrToInt
+ , attrToMaybe
+ , attrToMaybeInt
+ , attrToText
+
+ , elemToText
+ , elemToInt
+ , elemToMaybe
+ , elemWithAttrToText
+
+ , getMaybeFunction
+ , getElemWithSSID
+ , significant
+
+ , getAddress
+ , getCountry
+ , getDate
+ , getName
+ , getRelation
+ ) where
+
+import qualified Data.Text as T
+import Data.Tree.NTree.TypeDefs (NTree)
+
+import Text.XML.HXT.Core hiding (getName)
+
+import Robocop.Type
+import Robocop.SSL.XML.Type hiding (getVariant)
+
+
+
+-- | Find element with matching tag_name
+atElem :: ArrowXml a => String -> a (NTree XNode) XmlTree
+atElem elem' = deep ( isElem >>> hasName elem' )
+
+-- | Find a certain element with a specific attribute pair (tag and value)
+atElemWithAttr :: ArrowXml a => String -> String -> String -> a (NTree XNode) XmlTree
+atElemWithAttr elem' attr_name attr_val = deep ( isElem >>> hasName elem' >>> hasAttrValue attr_name (== attr_val) )
+
+
+
+-- | Get value of certain attribute and read it as an Int
+attrToInt :: ArrowXml a => String -> a (NTree XNode) Int
+attrToInt attr' = arr read <<< getAttrValue attr'
+
+-- | Get value of possible attribute
+attrToMaybe :: ArrowXml a => String -> a (NTree XNode) (Maybe String)
+attrToMaybe attr' = withDefault ( arr Just <<< isA significant <<< getAttrValue attr' ) Nothing
+
+-- | Get value of possible attribute and read it as an Int
+attrToMaybeInt :: ArrowXml a => String -> a (NTree XNode) (Maybe Int)
+attrToMaybeInt attr' = withDefault ( arr ( Just . read ) <<< isA significant <<< getAttrValue attr' ) Nothing
+
+-- | Get value of certain attribute and pack it as Text
+attrToText :: ArrowXml a => String -> a (NTree XNode) T.Text
+attrToText attr' = arr T.pack <<< getAttrValue attr'
+
+
+
+-- | Get value of certain element and read it as an Int
+elemToInt :: ArrowXml a => String -> a (NTree XNode) Int
+elemToInt elem' = arr read <<< getText <<< getChildren <<< atElem elem'
+
+-- | Get value of a possible element and pack is as Maybe Text
+elemToMaybe :: ArrowXml a => String -> a (NTree XNode) (Maybe T.Text)
+elemToMaybe elem' = withDefault ( arr ( Just . T.pack ) <<< isA significant <<< getText <<< getChildren <<< atElem elem' ) Nothing
+
+-- | Get value of certain element and pack it as Text
+elemToText :: ArrowXml a => String -> a (NTree XNode) T.Text
+elemToText elem' = arr T.pack <<< getText <<< getChildren <<< atElem elem'
+
+-- | Get value of certain element with specific attribute pair (tag and value) and pack it as Text
+elemWithAttrToText :: ArrowXml a => String -> String -> String -> a (NTree XNode) T.Text
+elemWithAttrToText elem' attr_name attr_val = arr T.pack <<< getText <<< getChildren <<< atElemWithAttr elem' attr_name attr_val
+
+
+
+-- | Check if a certain xml tag contains any significant values
+significant :: String -> Bool
+significant = not . all (`elem` " \n\r\t")
+
+-- | Get a parser of type a, return a parser of type Maybe a
+getMaybeFunction :: IOSLA (XIOState ()) (NTree XNode) a -> IOSLA (XIOState ()) (NTree XNode) (Maybe a)
+getMaybeFunction f = do withDefault ( arr Just <<< f ) Nothing
+
+-- | Get an element with SSID attribute and return WithSSID Text
+getElemWithSSID :: String -> IOSLA (XIOState ()) (NTree XNode) (WithSSID T.Text)
+getElemWithSSID elem' = atElem elem' >>>
+ proc x -> do
+ ssid <- attrToInt "ssid" -< x
+
+ val' <- getText <<< getChildren -< x
+
+ returnA -< WithSSID ssid (T.pack val')
+
+
+
+
+
+getAddress :: IOSLA (XIOState ()) (NTree XNode) (WithSSID (Quality Address))
+getAddress = atElem "address" >>>
+ proc addr -> do
+ ssid <- attrToInt "ssid" -< addr
+ quality <- getAttrValue "quality" -< addr
+
+ c_o' <- elemToMaybe "c-o" -< addr
+ details' <- elemToMaybe "address-details" -< addr
+ place_id' <- attrToInt "place-id" -< addr
+ p_o_box' <- elemToMaybe "p-o-box" -< addr
+ remark' <- elemToMaybe "remark" -< addr
+ zip_code' <- elemToMaybe "zip-code" -< addr
+
+ returnA -< WithSSID ssid $ stringToQuality quality $ Address
+ { c_o = c_o'
+ , details = details'
+ , place_id = place_id'
+ , p_o_box = p_o_box'
+ , remark = remark'
+ , zip_code = zip_code'
+ }
+
+
+
+getCountry :: String -> String -> IOSLA (XIOState ()) (NTree XNode) Country
+getCountry elem' attr' = atElem elem' >>>
+ proc country' -> do
+ name' <- arr T.pack <<< getText <<< getChildren -< country'
+ code' <- attrToText attr' -< country'
+
+ returnA -< Country
+ { country_name = name'
+ , country_code = code'
+ }
+
+
+
+getDate :: IOSLA (XIOState ()) (NTree XNode) (WithSSID (Quality Date))
+getDate = atElem "day-month-year" >>>
+ proc date' -> do
+ ssid <- attrToInt "ssid" -< date'
+ quality <- getAttrValue "quality" -< date'
+
+ day' <- attrToMaybeInt "day" -< date'
+ month' <- attrToMaybeInt "month" -< date'
+ year' <- attrToMaybeInt "year" -< date'
+ calendar' <- getAttrValue "calendar" -< date'
+
+ returnA -< WithSSID ssid $ stringToQuality quality $ Date
+ { day = day'
+ , month = month'
+ , year = case year' of Just y -> y; Nothing -> 2025;
+ , calendar = T.pack calendar'
+ }
+
+
+
+getName :: IOSLA (XIOState ()) (NTree XNode) (WithSSID (Quality Name))
+getName = atElem "name" >>>
+ proc name' -> do
+ ssid <- attrToInt "ssid" -< name'
+ quality <- getAttrValue "quality" -< name'
+
+ name_type' <- getAttrValue "name-type" -< name'
+ name_parts' <- listA getNamePart -< name'
+
+ returnA -< WithSSID ssid $ stringToQuality quality $ Name
+ { name_parts = name_parts'
+ , name_type = case name_type' of
+ "primary-name" -> PrimaryName
+ "alias" -> Alias
+ "formerly-known-as" -> FormerlyKnownAs
+ x -> (UnknownNameType . T.pack) x
+ }
+
+getNamePart :: IOSLA (XIOState ()) (NTree XNode) NamePart
+getNamePart = atElem "name-part" >>>
+ proc name_part -> do
+ name' <- elemToText "value" -< name_part
+ order' <- attrToInt "order" -< name_part
+ name_part_type' <- getAttrValue "name-part-type" -< name_part
+ variants' <- listA getSpellingVariant -< name_part
+
+ returnA -< NamePart
+ { name = name'
+ , order = order'
+ , variants = variants'
+ , name_part_type = case name_part_type' of
+ "family-name" -> FamilyName
+ "father-name" -> FatherName
+ "further-given-name" -> FurtherGivenName
+ "given-name" -> GivenName
+ "grand-father-name" -> GrandFatherName
+ "maiden-name" -> MaidenName
+ "suffix" -> Suffix
+ "title" -> Title
+ "tribal-name" -> TribalName
+ "whole-name" -> WholeName
+ "other" -> OtherNPT
+ x -> (UnknownNamePartType . T.pack) x
+ }
+
+getSpellingVariant :: IOSLA (XIOState ()) (NTree XNode) SpellingVariant
+getSpellingVariant = atElem "spelling-variant" >>>
+ proc spelling_variant -> do
+ language' <- getAttrValue "lang" -< spelling_variant
+ script' <- getAttrValue "script" -< spelling_variant
+ variant' <- getText <<< getChildren -< spelling_variant
+
+ returnA -< SpellingVariant
+ { language = T.pack language'
+ , script = T.pack script'
+ , variant = T.pack variant'
+ }
+
+
+
+getRelation :: IOSLA (XIOState ()) (NTree XNode) (WithSSID Relation)
+getRelation = atElem "relation" >>>
+ proc rel -> do
+ ssid <- attrToInt "ssid" -< rel
+
+ rel_target <- attrToInt "target-id" -< rel
+ rel_type <- getAttrValue "relation-type" -< rel
+
+ returnA -< WithSSID ssid $ Relation
+ { target_id = rel_target
+ , relation_type = case rel_type of
+ "related-to" -> RelatedTo
+ x -> (UnknownRelation . T.pack) x
+ }
diff --git a/src/Robocop/SSL/XML/Helpers/Type.hs b/src/Robocop/SSL/XML/Helpers/Type.hs
@@ -0,0 +1,97 @@
+-- SPDX-FileCopyrightText: 2025 LNRS
+--
+-- SPDX-License-Identifier: AGPL-3.0-or-later
+-- SPDX-License-Identifier: EUPL-1.2
+
+module Robocop.SSL.XML.Helpers.Type
+ ( Address(..)
+ , Country(..)
+ , Date(..)
+ , Name(..)
+ , NamePart(..)
+ , NamePartType(..)
+ , NameType(..)
+ , Relation(..)
+ , RelationType(..)
+ , SpellingVariant(..)
+ , WithSSID(..)
+ ) where
+
+import Data.Text
+
+import Robocop.Type
+
+
+
+data Address = Address
+ { c_o :: Maybe Text
+ , details :: Maybe Text
+ , p_o_box :: Maybe Text
+ , place_id :: Int
+ , remark :: Maybe Text
+ , zip_code :: Maybe Text
+ } deriving (Show, Eq)
+
+
+
+data Country = Country
+ { country_name :: Text
+ , country_code :: Text
+ } deriving (Show, Eq)
+
+
+
+data Date = Date
+ { day :: Maybe Int
+ , month :: Maybe Int
+ , year :: Int
+ , calendar :: Text
+ } deriving (Show, Eq)
+
+
+
+data Name = Name
+ { name_type :: NameType
+ , name_parts :: [NamePart]
+ } deriving (Show, Eq)
+
+data NameType = PrimaryName
+ | Alias
+ | FormerlyKnownAs
+ | UnknownNameType Text deriving (Show, Eq)
+
+data NamePart = NamePart
+ { name :: Text
+ , order :: Int
+ , name_part_type :: NamePartType
+ , variants :: [SpellingVariant]
+ } deriving (Show, Eq)
+
+data NamePartType = FamilyName
+ | FatherName
+ | FurtherGivenName
+ | GivenName
+ | GrandFatherName
+ | MaidenName
+ | Suffix
+ | Title
+ | TribalName
+ | WholeName
+ | OtherNPT
+ | UnknownNamePartType Text deriving (Show, Eq)
+
+data SpellingVariant = SpellingVariant
+ { language :: Text
+ , script :: Text
+ , variant :: Text
+ } deriving (Show, Eq)
+
+
+
+data Relation = Relation
+ { relation_type :: RelationType
+ , target_id :: Int
+ } deriving (Show, Eq)
+
+data RelationType = RelatedTo
+ | UnknownRelation Text deriving (Show, Eq)
diff --git a/src/Robocop/SSL/XML/Individual/Parse.hs b/src/Robocop/SSL/XML/Individual/Parse.hs
@@ -0,0 +1,119 @@
+-- SPDX-FileCopyrightText: 2025 LNRS
+--
+-- SPDX-License-Identifier: AGPL-3.0-or-later
+-- SPDX-License-Identifier: EUPL-1.2
+
+{-# LANGUAGE Arrows #-}
+{-# LANGUAGE BlockArguments #-}
+{-# LANGUAGE TemplateHaskell #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+
+module Robocop.SSL.XML.Individual.Parse
+ ( getIndividual
+ ) where
+
+import qualified Data.Text as T
+
+import Data.Tree.NTree.TypeDefs (NTree)
+
+import Text.XML.HXT.Core hiding (getName)
+
+import Robocop.Type
+import Robocop.SSL.XML.Type
+import Robocop.SSL.XML.Individual.Type
+import Robocop.SSL.XML.Helpers.Parse
+
+
+
+getIndividual :: IOSLA (XIOState ()) (NTree XNode) TargetType
+getIndividual = atElem "individual" >>>
+ proc ind -> do
+ WithSSID ssid identity <- getIndividualIdentity -< ind
+
+ sex' <- attrToMaybe "sex" -< ind
+ justifications' <- getMaybeFunction (listA $ getElemWithSSID "justification" ) -< ind
+ other_info' <- getMaybeFunction (listA $ getElemWithSSID "other-information") -< ind
+ relations' <- getMaybeFunction (listA getRelation) -< ind
+
+ returnA -< Ind $ WithSSID ssid $ Individual
+ { addresses = id_addresses identity
+ , birth_dates = id_birth_dates identity
+ , ids = id_ids identity
+ , names = id_names identity
+ , nationalities = id_nationalities identity
+ , sex = case sex' of
+ Just "male" -> Just Male
+ Just "female" -> Just Female
+ Just x -> (Just . UnknownSex . T.pack) x
+ Nothing -> Nothing
+ , justifications = justifications'
+ , other_info = other_info'
+ , relations = relations'
+ }
+
+
+
+getIndividualIdentity :: IOSLA (XIOState ()) (NTree XNode) (WithSSID IndividualIdentity)
+getIndividualIdentity = atElem "identity" >>>
+ proc identity -> do
+ ssid <- attrToInt "ssid" -< identity
+
+ addresses' <- getMaybeFunction (listA getAddress) -< identity
+ birth_dates' <- getMaybeFunction (listA getDate) -< identity
+ ids' <- getMaybeFunction (listA getIdentificationDocument) -< identity
+ names' <- listA getName -< identity
+ nationalities' <- getMaybeFunction (listA getNationality) -< identity
+
+ returnA -< WithSSID ssid $ IndividualIdentity
+ { id_addresses = addresses'
+ , id_birth_dates = birth_dates'
+ , id_ids = ids'
+ , id_names = names'
+ , id_nationalities = nationalities'
+ }
+
+
+
+getIdentificationDocument :: IOSLA (XIOState ()) (NTree XNode) (WithSSID IdentificationDocument)
+getIdentificationDocument = atElem "identification-document" >>>
+ proc doc -> do
+ ssid <- attrToInt "ssid" -< doc
+
+ number <- elemToText "number" -< doc
+ date_of_issue <- elemToMaybe "date-of-issue" -< doc
+ expiry_date <- elemToMaybe "expiry-date" -< doc
+ remark' <- elemToMaybe "remark" -< doc
+ id_type' <- getAttrValue "document-type" -< doc
+ -- place_of_issue <- attrToMaybeInt "place-id" <<< atElem "place-of-issue" -< doc
+ country' <- getCountry "issuer" "code" -< doc
+
+ returnA -< WithSSID ssid $ IdentificationDocument
+ { id_number = number
+ , id_issuer = country'
+ , id_remark = remark'
+ , id_date_of_issue = date_of_issue
+ -- , doc_place_of_issue = place_of_issue
+ , id_expiry_date = expiry_date
+ , id_type = case id_type' of
+ "diplomatic-passport" -> DiplomaticPassport
+ "driving-license" -> DrivingLicense
+ "driving-permit" -> DrivingPermit
+ "id-card" -> IDCard
+ "passport" -> Passport
+ "residence-permit" -> ResidencePermit
+ "travel-document" -> TravelDocument
+ "other" -> OtherIDType
+ x -> (UnknownIDType . T.pack) x
+
+ }
+
+
+
+getNationality :: IOSLA (XIOState ()) (NTree XNode) (WithSSID Country)
+getNationality = atElem "nationality" >>>
+ proc n -> do
+ ssid <- attrToInt "ssid" -< n
+
+ country' <- getCountry "country" "iso-code" -< n
+
+ returnA -< WithSSID ssid country'
diff --git a/src/Robocop/SSL/XML/Individual/Type.hs b/src/Robocop/SSL/XML/Individual/Type.hs
@@ -0,0 +1,61 @@
+-- SPDX-FileCopyrightText: 2025 LNRS
+--
+-- SPDX-License-Identifier: AGPL-3.0-or-later
+-- SPDX-License-Identifier: EUPL-1.2
+
+module Robocop.SSL.XML.Individual.Type
+ ( IdentificationDocument(..)
+ , IDType(..)
+ , Individual(..)
+ , IndividualIdentity(..)
+ , Sex(..)
+ ) where
+
+import Data.Text
+
+import Robocop.Type
+import Robocop.SSL.XML.Helpers.Type
+
+data Individual = Individual
+ { addresses :: Maybe [WithSSID (Quality Address)]
+ , birth_dates :: Maybe [WithSSID (Quality Date)]
+ , ids :: Maybe [WithSSID (IdentificationDocument)]
+ , names :: [WithSSID (Quality Name)]
+ , nationalities :: Maybe [WithSSID Country]
+ , sex :: Maybe Sex
+ , justifications :: Maybe [WithSSID Text]
+ , other_info :: Maybe [WithSSID Text]
+ , relations :: Maybe [WithSSID Relation]
+ } deriving (Show, Eq)
+
+data IndividualIdentity = IndividualIdentity
+ { id_addresses :: Maybe [WithSSID (Quality Address)]
+ , id_birth_dates :: Maybe [WithSSID (Quality Date)]
+ , id_ids :: Maybe [WithSSID IdentificationDocument]
+ , id_names :: [WithSSID (Quality Name)]
+ , id_nationalities :: Maybe [WithSSID Country]
+ } deriving (Show, Eq)
+
+data IdentificationDocument = IdentificationDocument
+ { id_number :: Text
+ , id_issuer :: Country
+ , id_date_of_issue :: Maybe Text
+ -- , doc_place_of_issue :: Maybe Int
+ , id_expiry_date :: Maybe Text
+ , id_remark :: Maybe Text
+ , id_type :: IDType
+ } deriving (Show, Eq)
+
+data IDType = DiplomaticPassport
+ | DrivingLicense
+ | DrivingPermit
+ | IDCard
+ | Passport
+ | ResidencePermit
+ | TravelDocument
+ | OtherIDType
+ | UnknownIDType Text deriving (Show, Eq)
+
+data Sex = Male
+ | Female
+ | UnknownSex Text deriving (Show, Eq)
diff --git a/src/Robocop/SSL/XML/Object/Parse.hs b/src/Robocop/SSL/XML/Object/Parse.hs
@@ -0,0 +1,53 @@
+-- SPDX-FileCopyrightText: 2025 LNRS
+--
+-- SPDX-License-Identifier: AGPL-3.0-or-later
+-- SPDX-License-Identifier: EUPL-1.2
+
+{-# LANGUAGE Arrows #-}
+{-# LANGUAGE BlockArguments #-}
+{-# LANGUAGE TemplateHaskell #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+
+module Robocop.SSL.XML.Object.Parse
+ ( getObject
+ ) where
+
+import qualified Data.Text as T
+import Data.Tree.NTree.TypeDefs (NTree)
+
+import Text.XML.HXT.Core hiding (getName)
+
+import Robocop.Type
+import Robocop.SSL.XML.Type
+import Robocop.SSL.XML.Object.Type
+
+import Robocop.SSL.XML.Helpers.Parse
+
+
+
+getObject :: IOSLA (XIOState ()) (NTree XNode) TargetType
+getObject = atElem "object" >>>
+ proc object -> do
+ WithSSID ssid names' <- getObjectIdentity -< object
+
+ object_type' <- getAttrValue "object-type" -< object
+ other_info' <- getMaybeFunction (listA $ getElemWithSSID "other-information") -< object
+
+ returnA -< Obj $ WithSSID ssid $ Object
+ { names = names'
+ , other_info = other_info'
+ , object_type = case object_type' of
+ "vessel" -> Vessel
+ x -> (UnknownObject . T.pack) x
+ }
+
+
+
+getObjectIdentity :: IOSLA (XIOState ()) (NTree XNode) (WithSSID [WithSSID (Quality Name)])
+getObjectIdentity = atElem "identity" >>>
+ proc id' -> do
+ ssid <- attrToInt "ssid" -< id'
+
+ names' <- listA getName -< id'
+
+ returnA -< WithSSID ssid names'
diff --git a/src/Robocop/SSL/XML/Object/Type.hs b/src/Robocop/SSL/XML/Object/Type.hs
@@ -0,0 +1,25 @@
+-- SPDX-FileCopyrightText: 2025 LNRS
+--
+-- SPDX-License-Identifier: AGPL-3.0-or-later
+-- SPDX-License-Identifier: EUPL-1.2
+
+module Robocop.SSL.XML.Object.Type
+ ( Object(..)
+ , ObjectType(..)
+ ) where
+
+import Data.Text
+
+import Robocop.Type
+import Robocop.SSL.XML.Helpers.Type
+
+
+
+data Object = Object
+ { object_type :: ObjectType
+ , names :: [WithSSID (Quality Name)]
+ , other_info :: Maybe [WithSSID Text]
+ } deriving (Show, Eq)
+
+data ObjectType = Vessel
+ | UnknownObject Text deriving (Show, Eq)
diff --git a/src/Robocop/SSL/XML/Parse.hs b/src/Robocop/SSL/XML/Parse.hs
@@ -0,0 +1,125 @@
+-- SPDX-FileCopyrightText: 2025 LNRS
+--
+-- SPDX-License-Identifier: AGPL-3.0-or-later
+-- SPDX-License-Identifier: EUPL-1.2
+
+{-# LANGUAGE Arrows #-}
+{-# LANGUAGE BlockArguments #-}
+{-# LANGUAGE TemplateHaskell #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+
+module Robocop.SSL.XML.Parse
+ ( parseSwissSanctionsList
+ ) where
+
+import Data.Tree.NTree.TypeDefs (NTree)
+
+import Text.XML.HXT.Core
+
+import Robocop.Type
+import Robocop.SSL.XML.Type hiding (getVariant)
+
+import Robocop.SSL.XML.Entity.Parse
+import Robocop.SSL.XML.Helpers.Parse
+import Robocop.SSL.XML.Individual.Parse
+import Robocop.SSL.XML.Object.Parse
+import Robocop.SSL.XML.Place.Parse
+
+
+
+parseSwissSanctionsList :: FilePath -> IO SwissSanctionsList
+parseSwissSanctionsList fp = do
+ [ sanction_list ] <- runX ( readDocument xmlConfig fp >>> getSwissSanctionsList )
+ return sanction_list
+
+-- | Config settings for xml parsing
+xmlConfig :: SysConfigList
+xmlConfig = [ withRemoveWS yes
+ , withValidate no
+ , withParseHTML no
+ ]
+
+
+
+getSwissSanctionsList :: IOSLA (XIOState ()) (NTree XNode) SwissSanctionsList
+getSwissSanctionsList = atElem "swiss-sanctions-list" >>>
+ proc ssl -> do
+ ssl_date <- attrToText "date" -< ssl
+ ssl_sanction_programs <- listA getSanctionProgram -< ssl
+ ssl_targets <- listA getTarget -< ssl
+ ssl_places <- listA getPlace -< ssl
+
+ returnA -< SwissSanctionsList
+ { date = ssl_date
+ , sanction_programs = ssl_sanction_programs
+ , targets = ssl_targets
+ , places = ssl_places
+ }
+
+
+
+getSanctionProgram :: IOSLA (XIOState ()) (NTree XNode) (WithSSID SanctionProgram)
+getSanctionProgram = atElem "sanctions-program" >>>
+ proc sanction_program -> do
+ ssid <- attrToInt "ssid" -< sanction_program
+
+ program_key' <- getTranslations "program-key" -< sanction_program
+ program_name' <- getTranslations "program-name" -< sanction_program
+ sanctions_set' <- getTranslationsWithSSID "sanctions-set" -< sanction_program
+ version_date' <- attrToText "version-date" -< sanction_program
+ predecessor_version_date' <- attrToText "predecessor-version-date" -< sanction_program
+ origin' <- elemToMaybe "origin" -< sanction_program
+
+ returnA -< WithSSID ssid $ SanctionProgram
+ { program_key = program_key'
+ , program_name = program_name'
+ , sanctions_set = sanctions_set'
+ , version_date = version_date'
+ , predecessor_version_date = predecessor_version_date'
+ , origin = origin'
+ }
+
+
+
+getTranslations :: String -> IOSLA (XIOState ()) (NTree XNode) Translations
+getTranslations elem' =
+ proc translations -> do
+ eng <- elemWithAttrToText elem' "lang" "eng" -< translations
+ ger <- elemWithAttrToText elem' "lang" "ger" -< translations
+ fre <- elemWithAttrToText elem' "lang" "fre" -< translations
+ ita <- elemWithAttrToText elem' "lang" "ita" -< translations
+
+ returnA -< Translations
+ { english = eng
+ , french = fre
+ , german = ger
+ , italian = ita
+ }
+
+
+
+getTranslationsWithSSID :: String -> IOSLA (XIOState ()) (NTree XNode) (WithSSID Translations)
+getTranslationsWithSSID elem' =
+ proc t -> do
+ ssid <- attrToInt "ssid" <<< atElemWithAttr elem' "lang" "eng" -< t
+
+ translations <- getTranslations elem' -< t
+
+ returnA -< WithSSID ssid translations
+
+
+
+getTarget :: IOSLA (XIOState ()) (NTree XNode) (WithSSID Target)
+getTarget = processTopDown (filterA $ neg (isElem >>> hasName "modification")) >>> atElem "target" >>>
+ proc target -> do
+ ssid <- attrToInt "ssid" -< target
+
+ sanctions_set_id' <- elemToInt "sanctions-set-id" -< target
+ foreign_identifier' <- elemToMaybe "foreign-identifier" -< target
+ target' <- getIndividual <+> getEntity <+> getObject -< target
+
+ returnA -< WithSSID ssid $ Target
+ { sanctions_set_id = sanctions_set_id'
+ , foreign_identifier = foreign_identifier'
+ , target_type = target'
+ }
diff --git a/src/Robocop/SSL/XML/Place/Parse.hs b/src/Robocop/SSL/XML/Place/Parse.hs
@@ -0,0 +1,57 @@
+-- SPDX-FileCopyrightText: 2025 LNRS
+--
+-- SPDX-License-Identifier: AGPL-3.0-or-later
+-- SPDX-License-Identifier: EUPL-1.2
+
+{-# LANGUAGE Arrows #-}
+{-# LANGUAGE BlockArguments #-}
+{-# LANGUAGE TemplateHaskell #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+
+module Robocop.SSL.XML.Place.Parse
+ ( getPlace
+ ) where
+
+import qualified Data.Text as T
+import Data.Tree.NTree.TypeDefs (NTree)
+
+import Text.XML.HXT.Core hiding (getName)
+
+import Robocop.Type
+import Robocop.SSL.XML.Type hiding (getVariant)
+
+import Robocop.SSL.XML.Helpers.Parse
+
+
+
+getPlace :: IOSLA (XIOState ()) (NTree XNode) (WithSSID Place)
+getPlace = atElem "place" >>>
+ proc p -> do
+ ssid <- attrToInt "ssid" -< p
+
+ area' <- elemToMaybe "area" -< p
+ location' <- elemToMaybe "location" -< p
+ area_variant' <- withDefault ( arr Just <<< getVariant "location-variant" ) Nothing -< p
+ location_variant' <- withDefault ( arr Just <<< getVariant "area-variant" ) Nothing -< p
+ country' <- withDefault ( arr Just <<< getCountry "country" "iso-code" ) Nothing -< p
+
+ returnA -< WithSSID ssid $ Place
+ { area = area'
+ , area_variant = area_variant'
+ , country = country'
+ , location = location'
+ , location_variant = location_variant'
+ }
+
+
+
+getVariant :: String -> IOSLA (XIOState ()) (NTree XNode) Variant
+getVariant elem' = atElem elem' >>>
+ proc x -> do
+ value <- arr T.pack <<< getText <<< getChildren -< x
+ variant_type <- getAttrValue "variant-type" -< x
+
+ returnA -< case variant_type of
+ "formerly-known-as" -> FKA value
+ "spelling-variant" -> Spelling value
+ _ -> Unknown value
diff --git a/src/Robocop/SSL/XML/Place/Type.hs b/src/Robocop/SSL/XML/Place/Type.hs
@@ -0,0 +1,37 @@
+-- SPDX-FileCopyrightText: 2025 LNRS
+--
+-- SPDX-License-Identifier: AGPL-3.0-or-later
+-- SPDX-License-Identifier: EUPL-1.2
+
+module Robocop.SSL.XML.Place.Type
+ ( Place(..)
+ , Variant(..)
+ , getVariant
+ ) where
+
+import Data.Text
+
+import Robocop.SSL.XML.Helpers.Type
+
+
+
+-- Place contains information about a specific country, location or area
+data Place = Place
+ { area :: Maybe Text
+ , area_variant :: Maybe Variant
+ , country :: Maybe Country
+ , location :: Maybe Text
+ , location_variant :: Maybe Variant
+ } deriving (Show, Eq)
+
+
+
+data Variant = Spelling Text
+ | FKA Text
+ | Unknown Text deriving (Show, Eq)
+
+getVariant :: Variant -> Maybe Text
+getVariant var = case var of
+ Spelling txt -> Just txt
+ FKA txt -> Just txt
+ _ -> Nothing
diff --git a/src/Robocop/SSL/XML/Type.hs b/src/Robocop/SSL/XML/Type.hs
@@ -0,0 +1,89 @@
+-- SPDX-FileCopyrightText: 2025 LNRS
+--
+-- SPDX-License-Identifier: AGPL-3.0-or-later
+-- SPDX-License-Identifier: EUPL-1.2
+
+module Robocop.SSL.XML.Type
+ ( Address(..)
+ , Country(..)
+ , Date(..)
+ , getNames
+ , getSSID
+ , getVariant
+ , IdentificationDocument(..)
+ , IDType(..)
+ , Name(..)
+ , NamePart(..)
+ , NamePartType(..)
+ , NameType(..)
+ , Place(..)
+ , Relation(..)
+ , RelationType(..)
+ , SanctionProgram(..)
+ , Sex(..)
+ , SpellingVariant(..)
+ , SwissSanctionsList(..)
+ , Target(..)
+ , TargetType(..)
+ , Translations(..)
+ , Variant(..)
+ , WithSSID(..)
+ ) where
+
+import Data.Text
+
+import Robocop.Type
+import Robocop.SSL.XML.Helpers.Type
+import Robocop.SSL.XML.Entity.Type as Ent
+import Robocop.SSL.XML.Individual.Type as Ind
+import Robocop.SSL.XML.Object.Type as Obj
+
+import Robocop.SSL.XML.Place.Type
+
+
+
+data SwissSanctionsList = SwissSanctionsList
+ { date :: Text
+ , sanction_programs :: [WithSSID SanctionProgram]
+ , targets :: [WithSSID Target]
+ , places :: [WithSSID Place]
+ } deriving (Show, Eq)
+
+
+
+-- SanctionProgram contains the specifics of the program
+data SanctionProgram = SanctionProgram
+ { program_key :: Translations
+ , program_name :: Translations
+ , sanctions_set :: WithSSID Translations
+ , version_date :: Text
+ , predecessor_version_date :: Text
+ , origin :: Maybe Text
+ } deriving (Show, Eq)
+
+data Translations = Translations
+ { english :: Text
+ , french :: Text
+ , german :: Text
+ , italian :: Text
+ } deriving (Show, Eq)
+
+
+
+-- Target contains the information about a sanctioned individual/entity/object
+data Target = Target
+ { sanctions_set_id :: Int
+ , foreign_identifier :: Maybe Text
+ , target_type :: TargetType
+ } deriving (Show, Eq)
+
+data TargetType = Ind (WithSSID Individual)
+ | Ent (WithSSID Entity)
+ | Obj (WithSSID Object) deriving (Show, Eq)
+
+
+
+getNames :: TargetType -> [WithSSID (Quality Name)]
+getNames (Ind (WithSSID _ ind)) = Ind.names ind
+getNames (Ent (WithSSID _ ent)) = Ent.names ent
+getNames (Obj (WithSSID _ obj)) = Obj.names obj
diff --git a/src/Robocop/Type.hs b/src/Robocop/Type.hs
@@ -0,0 +1,134 @@
+-- SPDX-FileCopyrightText: 2025 LNRS
+--
+-- SPDX-License-Identifier: AGPL-3.0-or-later
+-- SPDX-License-Identifier: EUPL-1.2
+
+
+{-# LANGUAGE DeriveGeneric #-}
+{-# LANGUAGE RecordWildCards #-}
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE PatternSynonyms #-}
+{-# LANGUAGE ViewPatterns #-}
+
+module Robocop.Type
+ ( getSSID
+ , liftQuality
+ , Quality(..)
+ , removeQuality
+ , removeSSID
+ , stringToQuality
+ , WithSSID(..)
+
+ , Day'(..)
+ , pattern YMD
+
+ , CommandLine(..)
+ , Config(..)
+ , TomlConfig(..)
+ , Verbosity(..)
+ ) where
+
+import GHC.Generics (Generic)
+
+import Data.Aeson (ToJSON(..), FromJSON(..), withText)
+import Data.Text (unpack)
+import Data.Time.Calendar
+import Data.Time.Format (defaultTimeLocale, parseTimeM)
+
+
+
+data Quality a = Good a
+ | Low a
+ | UnknownQuality a deriving (Show, Eq)
+
+liftQuality :: (a -> b) -> Quality a -> Quality b
+liftQuality func qual = case qual of
+ Good x -> Good $ func x
+ Low x -> Low $ func x
+ UnknownQuality x -> UnknownQuality $ func x
+
+removeQuality :: Quality a -> a
+removeQuality (Good x) = x
+removeQuality (Low x) = x
+removeQuality (UnknownQuality x) = x
+
+stringToQuality :: String -> a -> Quality a
+stringToQuality quality value = case quality of
+ "good" -> Good value
+ "low" -> Low value
+ _ -> UnknownQuality value
+
+data WithSSID a = WithSSID Int a deriving (Show, Eq)
+
+getSSID :: WithSSID a -> Int
+getSSID (WithSSID n _) = n
+
+removeSSID :: WithSSID a -> a
+removeSSID (WithSSID _ x) = x
+
+
+newtype Day' = Day' Day deriving (Show, Eq, Generic)
+
+instance FromJSON Day' where
+ parseJSON = withText "birthdate" $ \t ->
+ case parseTimeM False defaultTimeLocale "%Y-%-m-%-d" (unpack t) of
+ Just d -> pure $ Day' d
+ Nothing -> fail $ "Invalid Day format: " ++ unpack t
+
+instance ToJSON Day'
+
+pattern YMD :: Year -> MonthOfYear -> DayOfMonth -> Day'
+pattern YMD y m d <-
+ Day' (toGregorian -> (y,m,d))
+ where
+ YMD y m d = Day' $ fromGregorian y m d
+
+{-# COMPLETE YMD #-}
+
+
+-- | Data type containing all configuration information (robocop.conf)
+data Config = Config
+ { verbosity :: Verbosity
+ , ssl_location :: FilePath
+ , threshold_ratio :: Float
+ , threshold_points :: Float
+ , threshold_confidence :: Float
+ , perfect_points :: Float
+ , weight_address :: Float
+ , weight_date :: Float
+ , weight_id :: Float
+ , weight_name :: Float
+ , weight_nationality :: Float
+ } deriving (Show, Eq, Generic)
+
+data Verbosity = Test | Silent | Info | Errors | Debug deriving (Show, Eq, Generic, Ord)
+
+data TomlConfig = TomlConfig
+ { toml_verbosity :: Verbosity
+ , toml_ssl_location :: FilePath
+ , toml_threshold_ratio :: Float
+ , toml_threshold_points :: Float
+ , toml_threshold_confidence :: Float
+ , toml_perfect_points :: Float
+ , toml_weight_address :: Float
+ , toml_weight_date :: Float
+ , toml_weight_id :: Float
+ , toml_weight_name :: Float
+ , toml_weight_nationality :: Float
+ } deriving (Show, Eq, Generic)
+
+-- | Data type for user configuration via commandline
+data CommandLine = CommandLine
+ { cl_verbosity :: Maybe Verbosity
+ , cl_config_location :: FilePath
+ , cl_ssl_location :: Maybe FilePath
+ , cl_threshold_ratio :: Maybe Float
+ , cl_threshold_points :: Maybe Float
+ , cl_threshold_confidence :: Maybe Float
+ , cl_perfect_points :: Maybe Float
+ , cl_weight_address :: Maybe Float
+ , cl_weight_date :: Maybe Float
+ , cl_weight_id :: Maybe Float
+ , cl_weight_name :: Maybe Float
+ , cl_weight_nationality :: Maybe Float
+ } deriving (Show, Eq, Generic)
diff --git a/test/test-kycheck.hs b/test/test-robocop.hs