├── .gitignore ├── LICENSE.md ├── Nop.Plugin.Misc.MailChimp ├── Controllers │ ├── MailChimpController.cs │ └── MailChimpWebhookController.cs ├── Data │ └── SchemaMigration.cs ├── Domain │ ├── EntityType.cs │ ├── MailChimpSynchronizationRecord.cs │ ├── OperationResult.cs │ └── OperationType.cs ├── Infrastructure │ ├── NopStartup.cs │ └── RouteProvider.cs ├── MailChimpDefaults.cs ├── MailChimpPlugin.cs ├── MailChimpSettings.cs ├── Models │ └── ConfigurationModel.cs ├── Nop.Plugin.Misc.MailChimp.csproj ├── Notes.txt ├── Services │ ├── EventConsumer.cs │ ├── ISynchronizationRecordService.cs │ ├── MailChimpManager.cs │ ├── SynchronizationRecordService.cs │ └── SynchronizationTask.cs ├── Views │ ├── Configure.cshtml │ └── _ViewImports.cshtml ├── logo.png └── plugin.json └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | ################# 2 | ## Visual Studio 3 | ################# 4 | 5 | ## Ignore Visual Studio temporary files, build results, and 6 | ## files generated by popular Visual Studio add-ons. 7 | 8 | # User-specific files 9 | *.suo 10 | *.user 11 | *.sln.docstates 12 | 13 | # Build results 14 | 15 | .vs/ 16 | [Dd]ebug/ 17 | [Rr]elease/ 18 | x64/ 19 | [Bb]in/ 20 | [Oo]bj/ 21 | 22 | # MSTest test Results 23 | [Tt]est[Rr]esult*/ 24 | [Bb]uild[Ll]og.* 25 | 26 | *_i.c 27 | *_p.c 28 | *.ilk 29 | *.meta 30 | *.obj 31 | *.pch 32 | *.pdb 33 | *.pgc 34 | *.pgd 35 | *.rsp 36 | *.sbr 37 | *.tlb 38 | *.tli 39 | *.tlh 40 | *.tmp 41 | *.tmp_proj 42 | *.log 43 | *.vspscc 44 | *.vssscc 45 | .builds 46 | *.pidb 47 | *.log 48 | *.scc 49 | 50 | # Visual C++ cache files 51 | ipch/ 52 | *.aps 53 | *.ncb 54 | *.opensdf 55 | *.sdf 56 | *.cachefile 57 | 58 | # Visual Studio profiler 59 | *.psess 60 | *.vsp 61 | *.vspx 62 | 63 | # Guidance Automation Toolkit 64 | *.gpState 65 | 66 | # ReSharper is a .NET coding add-in 67 | _ReSharper*/ 68 | *.[Rr]e[Ss]harper 69 | 70 | # TeamCity is a build add-in 71 | _TeamCity* 72 | 73 | # DotCover is a Code Coverage Tool 74 | *.dotCover 75 | 76 | # NCrunch 77 | *.ncrunch* 78 | .*crunch*.local.xml 79 | 80 | # Installshield output folder 81 | [Ee]xpress/ 82 | 83 | # DocProject is a documentation generator add-in 84 | DocProject/buildhelp/ 85 | DocProject/Help/*.HxT 86 | DocProject/Help/*.HxC 87 | DocProject/Help/*.hhc 88 | DocProject/Help/*.hhk 89 | DocProject/Help/*.hhp 90 | DocProject/Help/Html2 91 | DocProject/Help/html 92 | 93 | # Click-Once directory 94 | publish/ 95 | 96 | # Publish Web Output 97 | *.Publish.xml 98 | *.pubxml 99 | 100 | # NuGet Packages Directory 101 | ## TODO: If you have NuGet Package Restore enabled, uncomment the next line 102 | #packages/ 103 | 104 | # Windows Azure Build Output 105 | csx 106 | *.build.csdef 107 | 108 | # Windows Store app package directory 109 | AppPackages/ 110 | 111 | # Others 112 | sql/ 113 | *.Cache 114 | ClientBin/ 115 | [Ss]tyle[Cc]op.* 116 | ~$* 117 | *~ 118 | *.dbmdl 119 | *.[Pp]ublish.xml 120 | *.pfx 121 | *.publishsettings 122 | 123 | # RIA/Silverlight projects 124 | Generated_Code/ 125 | 126 | # Backup & report files from converting an old project file to a newer 127 | # Visual Studio version. Backup files are not needed, because we have git ;-) 128 | _UpgradeReport_Files/ 129 | Backup*/ 130 | UpgradeLog*.XML 131 | UpgradeLog*.htm 132 | 133 | # SQL Server files 134 | App_Data/*.mdf 135 | App_Data/*.ldf 136 | 137 | ############# 138 | ## Windows detritus 139 | ############# 140 | 141 | # Windows image file caches 142 | Thumbs.db 143 | ehthumbs.db 144 | 145 | # Folder config file 146 | Desktop.ini 147 | 148 | # Recycle Bin used on file shares 149 | $RECYCLE.BIN/ 150 | 151 | # Mac crap 152 | .DS_Store 153 | 154 | 155 | ####################### 156 | ## nopCommerce specific 157 | ########### 158 | glob:*.user 159 | *.patch 160 | *.hg 161 | src/Presentation/Nop.Web/Plugins/* 162 | src/Presentation/Nop.Web/Content/Images/Thumbs/* 163 | src/Presentation/Nop.Web/App_Data/InstalledPlugins.txt 164 | src/Presentation/Nop.Web/App_Data/Settings.txt -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /Nop.Plugin.Misc.MailChimp/Controllers/MailChimpController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | using Microsoft.AspNetCore.Mvc.Rendering; 3 | using Nop.Core; 4 | using Nop.Core.Caching; 5 | using Nop.Core.Domain.ScheduleTasks; 6 | using Nop.Plugin.Misc.MailChimp.Domain; 7 | using Nop.Plugin.Misc.MailChimp.Models; 8 | using Nop.Plugin.Misc.MailChimp.Services; 9 | using Nop.Services.Configuration; 10 | using Nop.Services.Localization; 11 | using Nop.Services.Messages; 12 | using Nop.Services.ScheduleTasks; 13 | using Nop.Services.Stores; 14 | using Nop.Web.Framework; 15 | using Nop.Web.Framework.Controllers; 16 | using Nop.Web.Framework.Mvc; 17 | using Nop.Web.Framework.Mvc.Filters; 18 | 19 | namespace Nop.Plugin.Misc.MailChimp.Controllers; 20 | 21 | [AutoValidateAntiforgeryToken] 22 | [AuthorizeAdmin] 23 | [Area(AreaNames.ADMIN)] 24 | public class MailChimpController : BasePluginController 25 | { 26 | #region Fields 27 | 28 | private readonly ILocalizationService _localizationService; 29 | private readonly INotificationService _notificationService; 30 | private readonly IScheduleTaskService _scheduleTaskService; 31 | private readonly ISettingService _settingService; 32 | private readonly IStaticCacheManager _staticCacheManager; 33 | private readonly IStoreContext _storeContext; 34 | private readonly IStoreService _storeService; 35 | private readonly ISynchronizationRecordService _synchronizationRecordService; 36 | private readonly MailChimpManager _mailChimpManager; 37 | 38 | #endregion 39 | 40 | #region Ctor 41 | 42 | public MailChimpController( 43 | ILocalizationService localizationService, 44 | INotificationService notificationService, 45 | IScheduleTaskService scheduleTaskService, 46 | ISettingService settingService, 47 | IStaticCacheManager cacheManager, 48 | IStoreContext storeContext, 49 | IStoreService storeService, 50 | ISynchronizationRecordService synchronizationRecordService, 51 | MailChimpManager mailChimpManager) 52 | { 53 | _localizationService = localizationService; 54 | _notificationService = notificationService; 55 | _scheduleTaskService = scheduleTaskService; 56 | _settingService = settingService; 57 | _staticCacheManager = cacheManager; 58 | _storeContext = storeContext; 59 | _storeService = storeService; 60 | _synchronizationRecordService = synchronizationRecordService; 61 | _mailChimpManager = mailChimpManager; 62 | } 63 | 64 | #endregion 65 | 66 | #region Methods 67 | 68 | public async Task Configure() 69 | { 70 | //load settings for a chosen store scope 71 | var storeId = await _storeContext.GetActiveStoreScopeConfigurationAsync(); 72 | var mailChimpSettings = await _settingService.LoadSettingAsync(storeId); 73 | 74 | //prepare model 75 | var model = new ConfigurationModel 76 | { 77 | ApiKey = mailChimpSettings.ApiKey, 78 | PassEcommerceData = mailChimpSettings.PassEcommerceData, 79 | PassOnlySubscribed = mailChimpSettings.PassOnlySubscribed, 80 | ListId = mailChimpSettings.ListId, 81 | ListId_OverrideForStore = storeId > 0 && await _settingService.SettingExistsAsync(mailChimpSettings, settings => settings.ListId, storeId), 82 | ActiveStoreScopeConfiguration = storeId 83 | }; 84 | 85 | //check whether synchronization is in progress 86 | model.SynchronizationStarted = await _staticCacheManager.GetAsync(_staticCacheManager.PrepareKeyForDefaultCache(MailChimpDefaults.OperationNumberCacheKey), () => 0) != 0; 87 | 88 | //prepare account info 89 | if (!string.IsNullOrEmpty(mailChimpSettings.ApiKey)) 90 | model.AccountInfo = await _mailChimpManager.GetAccountInfoAsync(); 91 | 92 | //prepare available lists 93 | if (!string.IsNullOrEmpty(mailChimpSettings.ApiKey)) 94 | model.AvailableLists = await _mailChimpManager.GetAvailableListsAsync() ?? new List(); 95 | 96 | var defaultListId = mailChimpSettings.ListId; 97 | if (!model.AvailableLists.Any()) 98 | { 99 | //add the special item for 'there are no lists' with empty guid value 100 | model.AvailableLists.Add(new SelectListItem 101 | { 102 | Text = await _localizationService.GetResourceAsync("Plugins.Misc.MailChimp.Fields.List.NotExist"), 103 | Value = Guid.Empty.ToString() 104 | }); 105 | defaultListId = Guid.Empty.ToString(); 106 | } 107 | else if (string.IsNullOrEmpty(mailChimpSettings.ListId) || mailChimpSettings.ListId.Equals(Guid.Empty.ToString())) 108 | defaultListId = model.AvailableLists.FirstOrDefault()?.Value; 109 | 110 | //set the default list 111 | model.ListId = defaultListId; 112 | mailChimpSettings.ListId = defaultListId; 113 | await _settingService.SaveSettingOverridablePerStoreAsync(mailChimpSettings, settings => settings.ListId, model.ListId_OverrideForStore, storeId); 114 | 115 | //synchronization task 116 | var task = await _scheduleTaskService.GetTaskByTypeAsync(MailChimpDefaults.SynchronizationTask); 117 | if (task != null) 118 | { 119 | model.SynchronizationPeriod = task.Seconds / 60 / 60; 120 | model.AutoSynchronization = task.Enabled; 121 | } 122 | 123 | return View("~/Plugins/Misc.MailChimp/Views/Configure.cshtml", model); 124 | } 125 | 126 | [HttpPost, ActionName("Configure")] 127 | [FormValueRequired("save")] 128 | public async Task Configure(ConfigurationModel model) 129 | { 130 | if (!ModelState.IsValid) 131 | return await Configure(); 132 | 133 | //load settings for a chosen store scope 134 | var storeId = await _storeContext.GetActiveStoreScopeConfigurationAsync(); 135 | var mailChimpSettings = await _settingService.LoadSettingAsync(storeId); 136 | 137 | //update stores if the list was changed 138 | if (!string.IsNullOrEmpty(model.ListId) && !model.ListId.Equals(Guid.Empty.ToString()) && !model.ListId.Equals(mailChimpSettings.ListId)) 139 | { 140 | (storeId > 0 ? new[] { storeId } : (await _storeService.GetAllStoresAsync()).Select(store => store.Id)).ToList() 141 | .ForEach(id => _synchronizationRecordService.CreateOrUpdateRecordAsync(EntityType.Store, id, OperationType.Update)); 142 | } 143 | 144 | //prepare webhook 145 | if (!string.IsNullOrEmpty(mailChimpSettings.ApiKey)) 146 | { 147 | var listId = !string.IsNullOrEmpty(model.ListId) && !model.ListId.Equals(Guid.Empty.ToString()) ? model.ListId : string.Empty; 148 | var webhookPrepared = await _mailChimpManager.PrepareWebhookAsync(listId); 149 | 150 | //display warning if webhook is not prepared 151 | if (!webhookPrepared && !string.IsNullOrEmpty(listId)) 152 | _notificationService.WarningNotification(await _localizationService.GetResourceAsync("Plugins.Misc.MailChimp.Webhook.Warning")); 153 | } 154 | 155 | //save settings 156 | mailChimpSettings.ApiKey = model.ApiKey.Trim(); 157 | mailChimpSettings.PassEcommerceData = model.PassEcommerceData; 158 | mailChimpSettings.PassOnlySubscribed = model.PassOnlySubscribed; 159 | mailChimpSettings.ListId = model.ListId; 160 | await _settingService.SaveSettingAsync(mailChimpSettings, x => x.ApiKey, clearCache: false); 161 | await _settingService.SaveSettingAsync(mailChimpSettings, x => x.PassEcommerceData, clearCache: false); 162 | await _settingService.SaveSettingAsync(mailChimpSettings, x => x.PassOnlySubscribed, clearCache: false); 163 | await _settingService.SaveSettingOverridablePerStoreAsync(mailChimpSettings, x => x.ListId, model.ListId_OverrideForStore, storeId, false); 164 | await _settingService.ClearCacheAsync(); 165 | 166 | //create or update synchronization task 167 | var task = await _scheduleTaskService.GetTaskByTypeAsync(MailChimpDefaults.SynchronizationTask); 168 | if (task == null) 169 | { 170 | task = new ScheduleTask 171 | { 172 | Type = MailChimpDefaults.SynchronizationTask, 173 | Name = MailChimpDefaults.SynchronizationTaskName, 174 | Seconds = MailChimpDefaults.DefaultSynchronizationPeriod * 60 * 60 175 | }; 176 | await _scheduleTaskService.InsertTaskAsync(task); 177 | } 178 | 179 | var synchronizationPeriodInSeconds = model.SynchronizationPeriod * 60 * 60; 180 | var synchronizationEnabled = model.AutoSynchronization; 181 | if (task.Enabled != synchronizationEnabled || task.Seconds != synchronizationPeriodInSeconds) 182 | { 183 | //task parameters was changed 184 | task.Enabled = synchronizationEnabled; 185 | task.Seconds = synchronizationPeriodInSeconds; 186 | await _scheduleTaskService.UpdateTaskAsync(task); 187 | _notificationService.WarningNotification(await _localizationService.GetResourceAsync("Plugins.Misc.MailChimp.Fields.AutoSynchronization.Restart")); 188 | } 189 | 190 | _notificationService.SuccessNotification(await _localizationService.GetResourceAsync("Admin.Plugins.Saved")); 191 | 192 | return await Configure(); 193 | } 194 | 195 | [HttpPost, ActionName("Configure")] 196 | [FormValueRequired("synchronization")] 197 | public async Task Synchronization() 198 | { 199 | //ensure that user list for the synchronization is selected 200 | var mailChimpSettings = await _settingService.LoadSettingAsync(); 201 | if (string.IsNullOrEmpty(mailChimpSettings.ListId) || mailChimpSettings.ListId.Equals(Guid.Empty.ToString())) 202 | { 203 | _notificationService.ErrorNotification(await _localizationService.GetResourceAsync("Plugins.Misc.MailChimp.Synchronization.Error")); 204 | return await Configure(); 205 | } 206 | 207 | //start the synchronization 208 | var operationNumber = await _mailChimpManager.SynchronizeAsync(true); 209 | if (operationNumber > 0) 210 | { 211 | //cache number of operations 212 | await _staticCacheManager.RemoveAsync(MailChimpDefaults.SynchronizationBatchesCacheKey); 213 | await _staticCacheManager.SetAsync(_staticCacheManager.PrepareKeyForDefaultCache(MailChimpDefaults.OperationNumberCacheKey), operationNumber); 214 | 215 | _notificationService.SuccessNotification(await _localizationService.GetResourceAsync("Plugins.Misc.MailChimp.Synchronization.Started")); 216 | } 217 | else 218 | _notificationService.ErrorNotification(await _localizationService.GetResourceAsync("Plugins.Misc.MailChimp.Synchronization.Error")); 219 | 220 | return await Configure(); 221 | } 222 | 223 | public async Task IsSynchronizationComplete() 224 | { 225 | //try to get number of operations and already handled batches 226 | var operationNumber = await _staticCacheManager.GetAsync(_staticCacheManager.PrepareKeyForDefaultCache(MailChimpDefaults.OperationNumberCacheKey), () => 0); 227 | var batchesInfo = await _staticCacheManager.GetAsync(_staticCacheManager.PrepareKeyForDefaultCache(MailChimpDefaults.SynchronizationBatchesCacheKey), () => new Dictionary()); 228 | 229 | //check whether the synchronization is finished 230 | if (operationNumber == 0 || operationNumber == batchesInfo.Values.Sum()) 231 | { 232 | //clear cached values 233 | await _staticCacheManager.RemoveAsync(MailChimpDefaults.OperationNumberCacheKey); 234 | await _staticCacheManager.RemoveAsync(MailChimpDefaults.SynchronizationBatchesCacheKey); 235 | 236 | return Json(true); 237 | } 238 | 239 | return new NullJsonResult(); 240 | } 241 | 242 | #endregion 243 | } -------------------------------------------------------------------------------- /Nop.Plugin.Misc.MailChimp/Controllers/MailChimpWebhookController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Http; 2 | using Microsoft.AspNetCore.Mvc; 3 | using Nop.Core.Caching; 4 | using Nop.Plugin.Misc.MailChimp.Services; 5 | 6 | namespace Nop.Plugin.Misc.MailChimp.Controllers; 7 | 8 | public class MailChimpWebhookController : Controller 9 | { 10 | #region Fields 11 | 12 | private readonly IStaticCacheManager _staticCacheManager; 13 | private readonly MailChimpManager _mailChimpManager; 14 | 15 | #endregion 16 | 17 | #region Ctor 18 | 19 | public MailChimpWebhookController(IStaticCacheManager staticCacheManager, 20 | MailChimpManager mailChimpManager) 21 | { 22 | _staticCacheManager = staticCacheManager; 23 | _mailChimpManager = mailChimpManager; 24 | } 25 | 26 | #endregion 27 | 28 | #region Methods 29 | 30 | public IActionResult BatchWebhook() 31 | { 32 | return Ok(); 33 | } 34 | 35 | [HttpPost] 36 | [IgnoreAntiforgeryToken] 37 | public async Task BatchWebhook(IFormCollection form) 38 | { 39 | if (!Request.Form?.Any() ?? true) 40 | return BadRequest(); 41 | 42 | //try to get already handled batches 43 | var batchesInfo = await _staticCacheManager.GetAsync(_staticCacheManager.PrepareKeyForDefaultCache(MailChimpDefaults.SynchronizationBatchesCacheKey), () => new Dictionary()); 44 | 45 | //handle batch webhook 46 | var (id, completedOperationNumber) = await _mailChimpManager.HandleBatchWebhookAsync(Request.Form, batchesInfo); 47 | if (!string.IsNullOrEmpty(id) && completedOperationNumber.HasValue) 48 | { 49 | if (!batchesInfo.ContainsKey(id)) 50 | { 51 | //update cached value 52 | batchesInfo.Add(id, completedOperationNumber.Value); 53 | await _staticCacheManager.SetAsync(_staticCacheManager.PrepareKeyForDefaultCache(MailChimpDefaults.SynchronizationBatchesCacheKey), batchesInfo); 54 | } 55 | return Ok(); 56 | } 57 | return BadRequest(); 58 | } 59 | 60 | public IActionResult WebHook() 61 | { 62 | return Ok(); 63 | } 64 | 65 | [HttpPost] 66 | [IgnoreAntiforgeryToken] 67 | public async Task WebHook(IFormCollection form) 68 | { 69 | if (!Request.Form?.Any() ?? true) 70 | return BadRequest(); 71 | 72 | //handle webhook 73 | var success = await _mailChimpManager.HandleWebhookAsync(Request.Form); 74 | return success ? Ok() : BadRequest(); 75 | } 76 | 77 | #endregion 78 | } 79 | -------------------------------------------------------------------------------- /Nop.Plugin.Misc.MailChimp/Data/SchemaMigration.cs: -------------------------------------------------------------------------------- 1 | using FluentMigrator; 2 | using Nop.Data.Extensions; 3 | using Nop.Data.Migrations; 4 | using Nop.Plugin.Misc.MailChimp.Domain; 5 | 6 | namespace Nop.Plugin.Misc.MailChimp.Data; 7 | 8 | [NopMigration("2020/06/04 12:00:00", "Misc.MailChimp base schema", MigrationProcessType.Installation)] 9 | public class SchemaMigration : AutoReversingMigration 10 | { 11 | #region Methods 12 | 13 | /// 14 | /// Collect the UP migration expressions 15 | /// 16 | public override void Up() 17 | { 18 | Create.TableFor(); 19 | } 20 | 21 | #endregion 22 | } 23 | -------------------------------------------------------------------------------- /Nop.Plugin.Misc.MailChimp/Domain/EntityType.cs: -------------------------------------------------------------------------------- 1 | namespace Nop.Plugin.Misc.MailChimp.Domain; 2 | 3 | /// 4 | /// Represents an entity type enumeration 5 | /// 6 | public enum EntityType 7 | { 8 | /// 9 | /// Store 10 | /// 11 | Store, 12 | 13 | /// 14 | /// Customer 15 | /// 16 | Customer, 17 | 18 | /// 19 | /// Email subscription 20 | /// 21 | Subscription, 22 | 23 | /// 24 | /// Order 25 | /// 26 | Order, 27 | 28 | /// 29 | /// Product 30 | /// 31 | Product, 32 | 33 | /// 34 | /// Product attribute combination 35 | /// 36 | AttributeCombination 37 | } -------------------------------------------------------------------------------- /Nop.Plugin.Misc.MailChimp/Domain/MailChimpSynchronizationRecord.cs: -------------------------------------------------------------------------------- 1 | using Nop.Core; 2 | 3 | namespace Nop.Plugin.Misc.MailChimp.Domain; 4 | 5 | /// 6 | /// Represents a record pointing at the entity ready to synchronization 7 | /// 8 | public class MailChimpSynchronizationRecord : BaseEntity 9 | { 10 | /// 11 | /// Gets or sets an entity type identifier 12 | /// 13 | public int EntityTypeId { get; set; } 14 | 15 | /// 16 | /// Gets or sets an entity identifier 17 | /// 18 | public int EntityId { get; set; } 19 | 20 | /// 21 | /// Gets or sets an operation type identifier 22 | /// 23 | public int OperationTypeId { get; set; } 24 | 25 | /// 26 | /// Gets or sets an email (used only for subscriptions) 27 | /// 28 | public string Email { get; set; } 29 | 30 | /// 31 | /// Gets or sets a product identifier (used only for product attribute combinations) 32 | /// 33 | public int ProductId { get; set; } 34 | 35 | /// 36 | /// Gets or sets an entity type 37 | /// 38 | public EntityType EntityType 39 | { 40 | get => (EntityType)EntityTypeId; 41 | set => EntityTypeId = (int)value; 42 | } 43 | 44 | /// 45 | /// Gets or sets an operation type 46 | /// 47 | public OperationType OperationType 48 | { 49 | get => (OperationType)OperationTypeId; 50 | set => OperationTypeId = (int)value; 51 | } 52 | } -------------------------------------------------------------------------------- /Nop.Plugin.Misc.MailChimp/Domain/OperationResult.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | 3 | namespace Nop.Plugin.Misc.MailChimp.Domain; 4 | 5 | /// 6 | /// Represents operation result 7 | /// 8 | public class OperationResult 9 | { 10 | [JsonProperty(PropertyName = "status_code")] 11 | public string StatusCode { get; set; } 12 | 13 | [JsonProperty(PropertyName = "operation_id")] 14 | public string OperationId { get; set; } 15 | 16 | [JsonProperty(PropertyName = "response")] 17 | public string ResponseString { get; set; } 18 | } -------------------------------------------------------------------------------- /Nop.Plugin.Misc.MailChimp/Domain/OperationType.cs: -------------------------------------------------------------------------------- 1 | namespace Nop.Plugin.Misc.MailChimp.Domain; 2 | 3 | /// 4 | /// Represents an operation type enumeration 5 | /// 6 | public enum OperationType 7 | { 8 | /// 9 | /// Read 10 | /// 11 | Read, 12 | 13 | /// 14 | /// Create 15 | /// 16 | Create, 17 | 18 | /// 19 | /// Update 20 | /// 21 | Update, 22 | 23 | /// 24 | /// Delete 25 | /// 26 | Delete, 27 | 28 | /// 29 | /// Create or update 30 | /// 31 | CreateOrUpdate 32 | } -------------------------------------------------------------------------------- /Nop.Plugin.Misc.MailChimp/Infrastructure/NopStartup.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Builder; 2 | using Microsoft.Extensions.Configuration; 3 | using Microsoft.Extensions.DependencyInjection; 4 | using Nop.Core.Infrastructure; 5 | using Nop.Plugin.Misc.MailChimp.Services; 6 | 7 | namespace Nop.Plugin.Misc.MailChimp.Infrastructure; 8 | 9 | /// 10 | /// Represents object for the configuring services on application startup 11 | /// 12 | public class NopStartup : INopStartup 13 | { 14 | /// 15 | /// Add and configure any of the middleware 16 | /// 17 | /// Collection of service descriptors 18 | /// Configuration of the application 19 | public void ConfigureServices(IServiceCollection services, IConfiguration configuration) 20 | { 21 | //register MailChimp manager 22 | services.AddScoped(); 23 | 24 | //register custom data services 25 | services.AddScoped(); 26 | } 27 | 28 | /// 29 | /// Configure the using of added middleware 30 | /// 31 | /// Builder for configuring an application's request pipeline 32 | public void Configure(IApplicationBuilder application) 33 | { 34 | } 35 | 36 | /// 37 | /// Gets order of this startup configuration implementation 38 | /// 39 | public int Order => 3000; 40 | } 41 | -------------------------------------------------------------------------------- /Nop.Plugin.Misc.MailChimp/Infrastructure/RouteProvider.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Builder; 2 | using Microsoft.AspNetCore.Routing; 3 | using Nop.Web.Framework.Mvc.Routing; 4 | 5 | namespace Nop.Plugin.Misc.MailChimp.Infrastructure; 6 | 7 | /// 8 | /// Represents a plugin route provider 9 | /// 10 | public class RouteProvider : IRouteProvider 11 | { 12 | /// 13 | /// Register routes 14 | /// 15 | /// Route builder 16 | public void RegisterRoutes(IEndpointRouteBuilder endpointRouteBuilder) 17 | { 18 | //webhook routes 19 | endpointRouteBuilder.MapControllerRoute(MailChimpDefaults.BatchWebhookRoute, 20 | "Plugins/MailChimp/BatchWebhook", 21 | new { controller = "MailChimpWebhook", action = "BatchWebhook" }); 22 | 23 | endpointRouteBuilder.MapControllerRoute(MailChimpDefaults.WebhookRoute, 24 | "Plugins/MailChimp/Webhook", 25 | new { controller = "MailChimpWebhook", action = "WebHook" }); 26 | } 27 | 28 | /// 29 | /// Gets a priority of route provider 30 | /// 31 | public int Priority => 0; 32 | 33 | } -------------------------------------------------------------------------------- /Nop.Plugin.Misc.MailChimp/MailChimpDefaults.cs: -------------------------------------------------------------------------------- 1 | using Nop.Core.Caching; 2 | 3 | namespace Nop.Plugin.Misc.MailChimp; 4 | 5 | /// 6 | /// Represents MailChimp plugin constants 7 | /// 8 | public class MailChimpDefaults 9 | { 10 | /// 11 | /// Plugin system name 12 | /// 13 | public static string SystemName => "Misc.MailChimp"; 14 | 15 | /// 16 | /// Cache key to store the operation number of a synchronization 17 | /// 18 | public static CacheKey OperationNumberCacheKey => new("MailChimp-synchronization-operations"); 19 | 20 | /// 21 | /// Cache key to store handled batches of a synchronization 22 | /// 23 | public static CacheKey SynchronizationBatchesCacheKey => new("MailChimp-synchronization-batches"); 24 | 25 | /// 26 | /// Default mask of store identifier that uniquely identifying the store in MailChimp E-Commerce 27 | /// 28 | /// 29 | /// {0} : Store identifier 30 | /// 31 | public static string DefaultStoreIdMask => "nopCommerce-store-{0}"; 32 | 33 | /// 34 | /// Name of the route to the batch webhook handler 35 | /// 36 | public static string BatchWebhookRoute => "Plugin.Misc.MailChimp.BatchWebhook"; 37 | 38 | /// 39 | /// Name of the route to the webhook handler 40 | /// 41 | public static string WebhookRoute => "Plugin.Misc.MailChimp.Webhook"; 42 | 43 | /// 44 | /// An HTTP PATCH protocol method 45 | /// 46 | public static string PatchRequestMethod => "PATCH"; 47 | 48 | /// 49 | /// An HTTP DELETE protocol method 50 | /// 51 | public static string DeleteRequestMethod => "DELETE"; 52 | 53 | /// 54 | /// Merge field of a subscription member that contains a first name 55 | /// 56 | public static string FirstNameMergeField => "FNAME"; 57 | 58 | /// 59 | /// Merge field of a subscription member that contains a last name 60 | /// 61 | public static string LastNameMergeField => "LNAME"; 62 | 63 | /// 64 | /// Path of API request to manage subscription members 65 | /// 66 | /// {0} : List identifier 67 | /// {1} : Email hash 68 | /// 69 | public static string MembersApiPath => "/lists/{0}/members/{1}"; 70 | 71 | /// 72 | /// Path of API request to manage stores 73 | /// 74 | /// {0} : Store identifier 75 | /// 76 | public static string StoresApiPath => "/ecommerce/stores/{0}"; 77 | 78 | /// 79 | /// Path of API request to manage customers 80 | /// 81 | /// {0} : Store identifier 82 | /// {1} : Customer identifier 83 | /// 84 | public static string CustomersApiPath => "/ecommerce/stores/{0}/customers/{1}"; 85 | 86 | /// 87 | /// Path of API request to manage products 88 | /// 89 | /// {0} : Store identifier 90 | /// {1} : Product identifier 91 | /// 92 | public static string ProductsApiPath => "/ecommerce/stores/{0}/products/{1}"; 93 | 94 | /// 95 | /// Path of API request to manage product variants 96 | /// 97 | /// {0} : Store identifier 98 | /// {1} : Product identifier 99 | /// {2} : Product variant identifier 100 | /// 101 | public static string ProductVariantsApiPath => "/ecommerce/stores/{0}/products/{1}/variants/{2}"; 102 | 103 | /// 104 | /// Path of API request to manage orders 105 | /// 106 | /// {0} : Store identifier 107 | /// {1} : Order identifier 108 | /// 109 | public static string OrdersApiPath => "/ecommerce/stores/{0}/orders/{1}"; 110 | 111 | /// 112 | /// Path of API request to manage carts 113 | /// 114 | /// {0} : Store identifier 115 | /// {1} : Cart identifier 116 | /// 117 | public static string CartsApiPath => "/ecommerce/stores/{0}/carts/{1}"; 118 | 119 | /// 120 | /// Name of the synchronization task 121 | /// 122 | public static string SynchronizationTaskName => "Synchronization with MailChimp"; 123 | 124 | /// 125 | /// Type of the synchronization task 126 | /// 127 | public static string SynchronizationTask => "Nop.Plugin.Misc.MailChimp.Services.SynchronizationTask"; 128 | 129 | /// 130 | /// Default synchronization period in hours 131 | /// 132 | public static int DefaultSynchronizationPeriod => 6; 133 | 134 | /// 135 | /// Default batch operation number 136 | /// 137 | public static int DefaultBatchOperationNumber => 2000; 138 | } -------------------------------------------------------------------------------- /Nop.Plugin.Misc.MailChimp/MailChimpPlugin.cs: -------------------------------------------------------------------------------- 1 | using Nop.Core; 2 | using Nop.Core.Domain.ScheduleTasks; 3 | using Nop.Plugin.Misc.MailChimp.Services; 4 | using Nop.Services.Common; 5 | using Nop.Services.Configuration; 6 | using Nop.Services.Localization; 7 | using Nop.Services.Plugins; 8 | using Nop.Services.ScheduleTasks; 9 | using Task = System.Threading.Tasks.Task; 10 | 11 | namespace Nop.Plugin.Misc.MailChimp; 12 | 13 | /// 14 | /// Represents the MailChimp plugin 15 | /// 16 | public class MailChimpPlugin : BasePlugin, IMiscPlugin 17 | { 18 | #region Fields 19 | 20 | private readonly ILocalizationService _localizationService; 21 | private readonly IScheduleTaskService _scheduleTaskService; 22 | private readonly ISettingService _settingService; 23 | private readonly IWebHelper _webHelper; 24 | private readonly MailChimpManager _mailChimpManager; 25 | 26 | #endregion 27 | 28 | #region Ctor 29 | 30 | public MailChimpPlugin(ILocalizationService localizationService, 31 | IScheduleTaskService scheduleTaskService, 32 | ISettingService settingService, 33 | IWebHelper webHelper, 34 | MailChimpManager mailChimpManager) 35 | { 36 | _localizationService = localizationService; 37 | _scheduleTaskService = scheduleTaskService; 38 | _settingService = settingService; 39 | _webHelper = webHelper; 40 | _mailChimpManager = mailChimpManager; 41 | } 42 | 43 | #endregion 44 | 45 | #region Methods 46 | 47 | /// 48 | /// Gets a configuration page URL 49 | /// 50 | public override string GetConfigurationPageUrl() 51 | { 52 | return $"{_webHelper.GetStoreLocation()}Admin/MailChimp/Configure"; 53 | } 54 | 55 | /// 56 | /// Install the plugin 57 | /// 58 | /// A task that represents the asynchronous operation 59 | public override async Task InstallAsync() 60 | { 61 | //settings 62 | await _settingService.SaveSettingAsync(new MailChimpSettings 63 | { 64 | ListId = Guid.Empty.ToString(), 65 | StoreIdMask = MailChimpDefaults.DefaultStoreIdMask, 66 | BatchOperationNumber = MailChimpDefaults.DefaultBatchOperationNumber 67 | }); 68 | 69 | //synchronization task 70 | if (await _scheduleTaskService.GetTaskByTypeAsync(MailChimpDefaults.SynchronizationTask) == null) 71 | { 72 | await _scheduleTaskService.InsertTaskAsync(new ScheduleTask 73 | { 74 | Type = MailChimpDefaults.SynchronizationTask, 75 | Name = MailChimpDefaults.SynchronizationTaskName, 76 | Seconds = MailChimpDefaults.DefaultSynchronizationPeriod * 60 * 60 77 | }); 78 | } 79 | 80 | //locales 81 | await _localizationService.AddOrUpdateLocaleResourceAsync(new Dictionary 82 | { 83 | ["Plugins.Misc.MailChimp.Fields.AccountInfo"] = "Account information", 84 | ["Plugins.Misc.MailChimp.Fields.AccountInfo.Hint"] = "Display MailChimp account information.", 85 | ["Plugins.Misc.MailChimp.Fields.ApiKey"] = "API key", 86 | ["Plugins.Misc.MailChimp.Fields.ApiKey.Hint"] = "Enter your MailChimp account API key.", 87 | ["Plugins.Misc.MailChimp.Fields.AutoSynchronization"] = "Use auto synchronization", 88 | ["Plugins.Misc.MailChimp.Fields.AutoSynchronization.Hint"] = "Determine whether to use auto synchronization.", 89 | ["Plugins.Misc.MailChimp.Fields.AutoSynchronization.Restart"] = "Auto synchronization parameters has been changed, please restart the application", 90 | ["Plugins.Misc.MailChimp.Fields.List"] = "List", 91 | ["Plugins.Misc.MailChimp.Fields.List.Hint"] = "Choose list of users for the synchronization.", 92 | ["Plugins.Misc.MailChimp.Fields.List.NotExist"] = "There are no lists", 93 | ["Plugins.Misc.MailChimp.Fields.PassEcommerceData"] = "Pass E-Commerce data", 94 | ["Plugins.Misc.MailChimp.Fields.PassEcommerceData.Hint"] = "Determine whether to pass E-Commerce data (customers, products, orders, etc).", 95 | ["Plugins.Misc.MailChimp.Fields.PassOnlySubscribed"] = "Pass only subscribed customers", 96 | ["Plugins.Misc.MailChimp.Fields.PassOnlySubscribed.Hint"] = "Determine whether to pass only customers who are subscribers.", 97 | ["Plugins.Misc.MailChimp.Fields.SynchronizationPeriod"] = "Synchronization period", 98 | ["Plugins.Misc.MailChimp.Fields.SynchronizationPeriod.Hint"] = "Specify the synchronization period in hours.", 99 | ["Plugins.Misc.MailChimp.ManualSynchronization"] = "Synchronize", 100 | ["Plugins.Misc.MailChimp.ManualSynchronization.Hint"] = "Manually synchronize", 101 | ["Plugins.Misc.MailChimp.Synchronization.Error"] = "An error occurred during synchronization with MailChimp", 102 | ["Plugins.Misc.MailChimp.Synchronization.Started"] = "Synchronization is in progress", 103 | ["Plugins.Misc.MailChimp.Webhook.Warning"] = "Webhook was not created (you'll not be able to get unsubscribed users)" 104 | }); 105 | await base.InstallAsync(); 106 | } 107 | 108 | /// 109 | /// Uninstall the plugin 110 | /// 111 | /// A task that represents the asynchronous operation 112 | public override async Task UninstallAsync() 113 | { 114 | //webhooks 115 | await _mailChimpManager.DeleteBatchWebhookAsync(); 116 | await _mailChimpManager.DeleteWebhooksAsync(); 117 | 118 | //synchronization task 119 | var task = await _scheduleTaskService.GetTaskByTypeAsync(MailChimpDefaults.SynchronizationTask); 120 | if (task != null) 121 | await _scheduleTaskService.DeleteTaskAsync(task); 122 | 123 | //settings 124 | await _settingService.DeleteSettingAsync(); 125 | 126 | //locales 127 | await _localizationService.DeleteLocaleResourcesAsync("Plugins.Misc.MailChimp"); 128 | 129 | await base.UninstallAsync(); 130 | } 131 | 132 | #endregion 133 | } -------------------------------------------------------------------------------- /Nop.Plugin.Misc.MailChimp/MailChimpSettings.cs: -------------------------------------------------------------------------------- 1 | using Nop.Core.Configuration; 2 | 3 | namespace Nop.Plugin.Misc.MailChimp; 4 | 5 | /// 6 | /// Represents MailChimp plugin settings 7 | /// 8 | public class MailChimpSettings : ISettings 9 | { 10 | /// 11 | /// Gets or sets the API key 12 | /// 13 | public string ApiKey { get; set; } 14 | 15 | /// 16 | /// Gets or sets value indicating whether to pass E-Commerce data (customers, products, orders, etc) to MailChimp 17 | /// 18 | public bool PassEcommerceData { get; set; } 19 | 20 | /// 21 | /// Gets or sets value indicating whether to pass only customers who are subscribers to MailChimp 22 | /// 23 | public bool PassOnlySubscribed { get; set; } 24 | 25 | /// 26 | /// Gets or sets identifier of user list 27 | /// 28 | public string ListId { get; set; } 29 | 30 | /// 31 | /// Gets or sets mask of store identifier that uniquely identifying the store in MailChimp E-Commerce 32 | /// 33 | public string StoreIdMask { get; set; } 34 | 35 | /// 36 | /// Gets or sets number of an operation in the batch 37 | /// 38 | public int BatchOperationNumber { get; set; } 39 | } -------------------------------------------------------------------------------- /Nop.Plugin.Misc.MailChimp/Models/ConfigurationModel.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc.Rendering; 2 | using Nop.Web.Framework.Mvc.ModelBinding; 3 | using System.ComponentModel.DataAnnotations; 4 | 5 | namespace Nop.Plugin.Misc.MailChimp.Models; 6 | 7 | /// 8 | /// Represents MailChimp configuration model 9 | /// 10 | public record ConfigurationModel 11 | { 12 | #region Ctor 13 | 14 | public ConfigurationModel() 15 | { 16 | AvailableLists = new List(); 17 | } 18 | 19 | #endregion 20 | 21 | #region Properties 22 | 23 | public int ActiveStoreScopeConfiguration { get; set; } 24 | 25 | public bool SynchronizationStarted { get; set; } 26 | 27 | [NopResourceDisplayName("Plugins.Misc.MailChimp.Fields.ApiKey")] 28 | [DataType(DataType.Password)] 29 | public string ApiKey { get; set; } 30 | 31 | [NopResourceDisplayName("Plugins.Misc.MailChimp.Fields.AccountInfo")] 32 | public string AccountInfo { get; set; } 33 | 34 | [NopResourceDisplayName("Plugins.Misc.MailChimp.Fields.PassEcommerceData")] 35 | public bool PassEcommerceData { get; set; } 36 | 37 | [NopResourceDisplayName("Plugins.Misc.MailChimp.Fields.PassOnlySubscribed")] 38 | public bool PassOnlySubscribed { get; set; } 39 | 40 | [NopResourceDisplayName("Plugins.Misc.MailChimp.Fields.List")] 41 | public string ListId { get; set; } 42 | public bool ListId_OverrideForStore { get; set; } 43 | public IList AvailableLists { get; set; } 44 | 45 | [NopResourceDisplayName("Plugins.Misc.MailChimp.Fields.AutoSynchronization")] 46 | public bool AutoSynchronization { get; set; } 47 | 48 | [NopResourceDisplayName("Plugins.Misc.MailChimp.Fields.SynchronizationPeriod")] 49 | public int SynchronizationPeriod { get; set; } 50 | 51 | #endregion 52 | } -------------------------------------------------------------------------------- /Nop.Plugin.Misc.MailChimp/Nop.Plugin.Misc.MailChimp.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net9.0 5 | Copyright © Nop Solutions, Ltd 6 | Nop Solutions, Ltd 7 | Nop Solutions, Ltd 8 | https://github.com/nopSolutions/mailchimp-plugin-for-nopcommerce/blob/nopCommerce-4.40/LICENSE.md 9 | https://www.nopcommerce.com/mailchimp-synchronization-plugin 10 | https://github.com/nopSolutions/mailchimp-plugin-for-nopcommerce 11 | Git 12 | $(SolutionDir)\Presentation\Nop.Web\Plugins\Misc.MailChimp 13 | $(OutputPath) 14 | 15 | true 16 | enable 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | Always 29 | 30 | 31 | Always 32 | 33 | 34 | Always 35 | 36 | 37 | Always 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | -------------------------------------------------------------------------------- /Nop.Plugin.Misc.MailChimp/Notes.txt: -------------------------------------------------------------------------------- 1 | Important points when developing plugins 2 | 3 | 4 | - All views (cshtml files) and web.config file should have "Build action" set to "Content" and "Copy to output directory" set to "Copy if newer" 5 | 6 | - When you develop a new plugin from scratch, and when a new class library is added to the solution, open its .csproj file (a main project file) in any text editor and replace its content with the following one 7 | 8 | 9 | 10 | net9.0 11 | $(SolutionDir)\Presentation\Nop.Web\Plugins\PLUGIN_OUTPUT_DIRECTORY 12 | $(OutputPath) 13 | 16 | false 17 | enable 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | Replace “PLUGIN_OUTPUT_DIRECTORY” in the code above with your real plugin output directory name. 32 | 33 | It’s not required. But this way we can use a new ASP.NET approach to add third-party references. It was introduced in .NET Core. Furthermore, references from already referenced libraries will be loaded automatically. It’s very convenient. -------------------------------------------------------------------------------- /Nop.Plugin.Misc.MailChimp/Services/EventConsumer.cs: -------------------------------------------------------------------------------- 1 | using Nop.Core.Domain.Catalog; 2 | using Nop.Core.Domain.Customers; 3 | using Nop.Core.Domain.Messages; 4 | using Nop.Core.Domain.Orders; 5 | using Nop.Core.Domain.Stores; 6 | using Nop.Core.Events; 7 | using Nop.Plugin.Misc.MailChimp.Domain; 8 | using Nop.Services.Catalog; 9 | using Nop.Services.Customers; 10 | using Nop.Services.Events; 11 | 12 | namespace Nop.Plugin.Misc.MailChimp.Services; 13 | 14 | /// 15 | /// Represents an event consumer that prepares records for the synchronization 16 | /// 17 | public class EventConsumer : 18 | //stores 19 | IConsumer>, 20 | IConsumer>, 21 | IConsumer>, 22 | //customers 23 | IConsumer, 24 | IConsumer>, 25 | IConsumer>, 26 | //subscriptions 27 | IConsumer, 28 | IConsumer>, 29 | IConsumer>, 30 | IConsumer>, 31 | //products 32 | IConsumer>, 33 | IConsumer>, 34 | //product attribute 35 | IConsumer>, 36 | IConsumer>, 37 | //attribute values 38 | IConsumer>, 39 | IConsumer>, 40 | //attribute combinations 41 | IConsumer>, 42 | IConsumer>, 43 | IConsumer>, 44 | //orders 45 | IConsumer>, 46 | IConsumer> 47 | { 48 | #region Fields 49 | 50 | private readonly ICustomerService _customerService; 51 | private readonly IProductAttributeParser _productAttributeParser; 52 | private readonly IProductAttributeService _productAttributeService; 53 | private readonly IProductService _productService; 54 | private readonly ISynchronizationRecordService _synchronizationRecordService; 55 | 56 | #endregion 57 | 58 | #region Ctor 59 | 60 | public EventConsumer(ICustomerService customerService, 61 | IProductAttributeParser productAttributeParser, 62 | IProductAttributeService productAttributeService, 63 | IProductService productService, 64 | ISynchronizationRecordService synchronizationRecordService) 65 | { 66 | _customerService = customerService; 67 | _productAttributeParser = productAttributeParser; 68 | _productAttributeService = productAttributeService; 69 | _productService = productService; 70 | _synchronizationRecordService = synchronizationRecordService; 71 | } 72 | 73 | #endregion 74 | 75 | #region Utilities 76 | 77 | /// 78 | /// Create or update the synchronization record with passed parameters 79 | /// 80 | /// Entity type 81 | /// Entity identifier 82 | /// Operation type 83 | /// Subscription email 84 | /// Product identifier 85 | private void AddRecord(EntityType entityType, int? id, OperationType operationType, string email = null, int? productId = null) 86 | { 87 | _synchronizationRecordService.CreateOrUpdateRecordAsync(entityType, id ?? 0, operationType, email, productId ?? 0); 88 | } 89 | 90 | #endregion 91 | 92 | #region Methods 93 | 94 | /// 95 | /// Handle the store inserted event 96 | /// 97 | /// Event message 98 | /// A task that represents the asynchronous operation 99 | public Task HandleEventAsync(EntityInsertedEvent eventMessage) 100 | { 101 | if (eventMessage.Entity != null) 102 | AddRecord(EntityType.Store, eventMessage.Entity.Id, OperationType.Create); 103 | 104 | return Task.CompletedTask; 105 | } 106 | 107 | /// 108 | /// Handle the store updated event 109 | /// 110 | /// Event message 111 | /// A task that represents the asynchronous operation 112 | public Task HandleEventAsync(EntityUpdatedEvent eventMessage) 113 | { 114 | if (eventMessage.Entity != null) 115 | AddRecord(EntityType.Store, eventMessage.Entity.Id, OperationType.Update); 116 | 117 | return Task.CompletedTask; 118 | } 119 | 120 | /// 121 | /// Handle the store deleted event 122 | /// 123 | /// Event message 124 | /// A task that represents the asynchronous operation 125 | public Task HandleEventAsync(EntityDeletedEvent eventMessage) 126 | { 127 | if (eventMessage.Entity != null) 128 | AddRecord(EntityType.Store, eventMessage.Entity.Id, OperationType.Delete); 129 | 130 | return Task.CompletedTask; 131 | } 132 | 133 | /// 134 | /// Handle the customer registered event 135 | /// 136 | /// Event message 137 | /// A task that represents the asynchronous operation 138 | public Task HandleEventAsync(CustomerRegisteredEvent eventMessage) 139 | { 140 | if (eventMessage.Customer != null) 141 | AddRecord(EntityType.Customer, eventMessage.Customer.Id, OperationType.Create); 142 | 143 | return Task.CompletedTask; 144 | } 145 | 146 | /// 147 | /// Handle the customer inserted event 148 | /// 149 | /// Event message 150 | /// A task that represents the asynchronous operation 151 | public async Task HandleEventAsync(EntityInsertedEvent eventMessage) 152 | { 153 | if (eventMessage.Entity == null || await _customerService.IsGuestAsync(eventMessage.Entity) || 154 | string.IsNullOrEmpty(eventMessage.Entity?.Email)) 155 | return; 156 | 157 | AddRecord(EntityType.Customer, eventMessage.Entity.Id, OperationType.Create); 158 | } 159 | 160 | /// 161 | /// Handle the customer updated event 162 | /// 163 | /// Event message 164 | /// A task that represents the asynchronous operation 165 | public async Task HandleEventAsync(EntityUpdatedEvent eventMessage) 166 | { 167 | if (eventMessage.Entity == null || await _customerService.IsGuestAsync(eventMessage.Entity) || 168 | string.IsNullOrEmpty(eventMessage.Entity?.Email)) 169 | return; 170 | 171 | var operationType = eventMessage.Entity.Deleted ? OperationType.Delete : OperationType.Update; 172 | AddRecord(EntityType.Customer, eventMessage.Entity.Id, operationType); 173 | } 174 | 175 | /// 176 | /// Handle the customer unsubscribed event 177 | /// 178 | /// Event message 179 | /// A task that represents the asynchronous operation 180 | public Task HandleEventAsync(EmailUnsubscribedEvent eventMessage) 181 | { 182 | if (eventMessage.Subscription != null) 183 | AddRecord(EntityType.Subscription, null, OperationType.Delete, eventMessage.Subscription.Email); 184 | 185 | return Task.CompletedTask; 186 | } 187 | 188 | /// 189 | /// Handle the newsletter subscription inserted event 190 | /// 191 | /// Event message 192 | /// A task that represents the asynchronous operation 193 | public Task HandleEventAsync(EntityInsertedEvent eventMessage) 194 | { 195 | if (eventMessage.Entity != null) 196 | AddRecord(EntityType.Subscription, eventMessage.Entity.Id, OperationType.Create); 197 | 198 | return Task.CompletedTask; 199 | } 200 | 201 | /// 202 | /// Handle the newsletter subscription updated event 203 | /// 204 | /// Event message 205 | /// A task that represents the asynchronous operation 206 | public Task HandleEventAsync(EntityUpdatedEvent eventMessage) 207 | { 208 | if (eventMessage.Entity != null) 209 | AddRecord(EntityType.Subscription, eventMessage.Entity.Id, OperationType.Update); 210 | 211 | return Task.CompletedTask; 212 | } 213 | 214 | /// 215 | /// Handle the newsletter subscription deleted event 216 | /// 217 | /// Event message 218 | /// A task that represents the asynchronous operation 219 | public Task HandleEventAsync(EntityDeletedEvent eventMessage) 220 | { 221 | if (eventMessage.Entity != null) 222 | AddRecord(EntityType.Subscription, eventMessage.Entity.Id, OperationType.Delete, eventMessage.Entity.Email); 223 | 224 | return Task.CompletedTask; 225 | } 226 | 227 | /// 228 | /// Handle the product inserted event 229 | /// 230 | /// Event message 231 | /// A task that represents the asynchronous operation 232 | public Task HandleEventAsync(EntityInsertedEvent eventMessage) 233 | { 234 | if (eventMessage.Entity != null) 235 | AddRecord(EntityType.Product, eventMessage.Entity.Id, OperationType.Create); 236 | 237 | return Task.CompletedTask; 238 | } 239 | 240 | /// 241 | /// Handle the product updated event 242 | /// 243 | /// Event message 244 | /// A task that represents the asynchronous operation 245 | public Task HandleEventAsync(EntityUpdatedEvent eventMessage) 246 | { 247 | if (eventMessage.Entity != null) 248 | { 249 | var operationType = eventMessage.Entity.Deleted ? OperationType.Delete : OperationType.Update; 250 | AddRecord(EntityType.Product, eventMessage.Entity.Id, operationType); 251 | } 252 | 253 | return Task.CompletedTask; 254 | } 255 | 256 | /// 257 | /// Handle the product attribute mapping deleted event 258 | /// 259 | /// Event message 260 | /// A task that represents the asynchronous operation 261 | public async Task HandleEventAsync(EntityDeletedEvent eventMessage) 262 | { 263 | if (eventMessage.Entity == null) 264 | return; 265 | 266 | //update combinations related with deleted product attribute mapping 267 | var combinations = (await _productAttributeService.GetAllProductAttributeCombinationsAsync(eventMessage.Entity.ProductId)) 268 | .WhereAwait(async combination => (await _productAttributeParser.ParseProductAttributeMappingsAsync(combination.AttributesXml)) 269 | .Any(productAttributeMapping => productAttributeMapping.Id == eventMessage.Entity.Id)); 270 | await foreach (var combination in combinations) 271 | { 272 | AddRecord(EntityType.AttributeCombination, combination.Id, OperationType.Update); 273 | } 274 | } 275 | 276 | /// 277 | /// Handle the product attribute deleted event 278 | /// 279 | /// Event message 280 | /// A task that represents the asynchronous operation 281 | public async Task HandleEventAsync(EntityDeletedEvent eventMessage) 282 | { 283 | if (eventMessage.Entity == null) 284 | return; 285 | 286 | //get associated product attribute mapping objects 287 | var productAttributeMappings = (await _productService.GetProductsByProductAttributeIdAsync(eventMessage.Entity.Id)) 288 | .SelectManyAwait(async product => (await _productAttributeService.GetProductAttributeMappingsByProductIdAsync(product.Id)) 289 | .Where(attribute => attribute.ProductId > 0 && attribute.ProductAttributeId == eventMessage.Entity.Id)); 290 | await foreach (var productAttributeMapping in productAttributeMappings) 291 | { 292 | //update combinations related with deleted product attribute 293 | var combinations = (await _productAttributeService.GetAllProductAttributeCombinationsAsync(productAttributeMapping.ProductId)) 294 | .WhereAwait(async combination => (await _productAttributeParser.ParseProductAttributeMappingsAsync(combination.AttributesXml)) 295 | .Any(mapping => mapping.Id == productAttributeMapping.Id)); 296 | await foreach (var combination in combinations) 297 | { 298 | AddRecord(EntityType.AttributeCombination, combination.Id, OperationType.Update); 299 | } 300 | } 301 | } 302 | 303 | /// 304 | /// Handle the product attribute value updated event 305 | /// 306 | /// Event message 307 | /// A task that represents the asynchronous operation 308 | public async Task HandleEventAsync(EntityUpdatedEvent eventMessage) 309 | { 310 | if (eventMessage.Entity == null) 311 | return; 312 | 313 | //get associated product attribute mapping object 314 | var productAttributeMapping = await _productAttributeService.GetProductAttributeMappingByIdAsync(eventMessage.Entity.ProductAttributeMappingId); 315 | if (productAttributeMapping == null) 316 | return; 317 | 318 | //update combinations related with updated product attribute value 319 | var combinations = (await _productAttributeService.GetAllProductAttributeCombinationsAsync(productAttributeMapping.ProductId)) 320 | .WhereAwait(async combination => (await _productAttributeParser.ParseProductAttributeValuesAsync(combination.AttributesXml, productAttributeMapping.Id)) 321 | .Any(value => value.Id == eventMessage.Entity.Id)); 322 | await foreach (var combination in combinations) 323 | { 324 | AddRecord(EntityType.AttributeCombination, combination.Id, OperationType.Update); 325 | } 326 | } 327 | 328 | /// 329 | /// Handle the product attribute value deleted event 330 | /// 331 | /// Event message 332 | /// A task that represents the asynchronous operation 333 | public async Task HandleEventAsync(EntityDeletedEvent eventMessage) 334 | { 335 | if (eventMessage.Entity == null) 336 | return; 337 | 338 | //get associated product attribute mapping object 339 | var productAttributeMapping = await _productAttributeService.GetProductAttributeMappingByIdAsync(eventMessage.Entity.ProductAttributeMappingId); 340 | if (productAttributeMapping == null) 341 | return; 342 | 343 | //update combinations related with deleted product attribute value 344 | var combinations = (await _productAttributeService.GetAllProductAttributeCombinationsAsync(productAttributeMapping.ProductId)) 345 | .WhereAwait(async combination => (await _productAttributeParser.ParseProductAttributeValuesAsync(combination.AttributesXml, productAttributeMapping.Id)) 346 | .Any(value => value.Id == eventMessage.Entity.Id)); 347 | await foreach (var combination in combinations) 348 | { 349 | AddRecord(EntityType.AttributeCombination, combination.Id, OperationType.Update); 350 | } 351 | } 352 | 353 | /// 354 | /// Handle the product attribute combination inserted event 355 | /// 356 | /// Event message 357 | /// A task that represents the asynchronous operation 358 | public Task HandleEventAsync(EntityInsertedEvent eventMessage) 359 | { 360 | if (eventMessage.Entity != null) 361 | AddRecord(EntityType.AttributeCombination, eventMessage.Entity.Id, OperationType.Create); 362 | 363 | return Task.CompletedTask; 364 | } 365 | 366 | /// 367 | /// Handle the product attribute combination updated event 368 | /// 369 | /// Event message 370 | /// A task that represents the asynchronous operation 371 | public Task HandleEventAsync(EntityUpdatedEvent eventMessage) 372 | { 373 | if (eventMessage.Entity != null) 374 | AddRecord(EntityType.AttributeCombination, eventMessage.Entity.Id, OperationType.Update); 375 | 376 | return Task.CompletedTask; 377 | } 378 | 379 | /// 380 | /// Handle the product attribute combination deleted event 381 | /// 382 | /// Event message 383 | /// A task that represents the asynchronous operation 384 | public Task HandleEventAsync(EntityDeletedEvent eventMessage) 385 | { 386 | if (eventMessage.Entity != null) 387 | AddRecord(EntityType.AttributeCombination, eventMessage.Entity.Id, OperationType.Delete, productId: eventMessage.Entity.ProductId); 388 | 389 | return Task.CompletedTask; 390 | } 391 | 392 | /// 393 | /// Handle the order inserted event 394 | /// 395 | /// Event message 396 | /// A task that represents the asynchronous operation 397 | public Task HandleEventAsync(EntityInsertedEvent eventMessage) 398 | { 399 | if (eventMessage.Entity != null) 400 | AddRecord(EntityType.Order, eventMessage.Entity.Id, OperationType.Create); 401 | 402 | return Task.CompletedTask; 403 | } 404 | 405 | /// 406 | /// Handle the order inserted event 407 | /// 408 | /// Event message 409 | /// A task that represents the asynchronous operation 410 | public Task HandleEventAsync(EntityUpdatedEvent eventMessage) 411 | { 412 | if (eventMessage.Entity != null) 413 | { 414 | var operationType = eventMessage.Entity.Deleted ? OperationType.Delete : OperationType.Update; 415 | AddRecord(EntityType.Order, eventMessage.Entity.Id, operationType); 416 | } 417 | 418 | return Task.CompletedTask; 419 | } 420 | 421 | #endregion 422 | } -------------------------------------------------------------------------------- /Nop.Plugin.Misc.MailChimp/Services/ISynchronizationRecordService.cs: -------------------------------------------------------------------------------- 1 | using Nop.Plugin.Misc.MailChimp.Domain; 2 | 3 | namespace Nop.Plugin.Misc.MailChimp.Services; 4 | 5 | /// 6 | /// Represents MailChimp synchronization record service 7 | /// 8 | public interface ISynchronizationRecordService 9 | { 10 | /// 11 | /// Get all synchronization records 12 | /// 13 | /// List of synchronization records 14 | IList GetAllRecords(); 15 | 16 | /// 17 | /// Get a synchronization record by identifier 18 | /// 19 | /// Synchronization record identifier 20 | /// Synchronization record 21 | Task GetRecordByIdAsync(int recordId); 22 | 23 | /// 24 | /// Get synchronization records by entity type and operation type 25 | /// 26 | /// Entity type 27 | /// Operation type 28 | /// List of aynchronization records 29 | IList GetRecordsByEntityTypeAndOperationType(EntityType entityType, OperationType operationType); 30 | 31 | /// 32 | /// Create the new one or update an existing synchronization record 33 | /// 34 | /// Entity type 35 | /// Entity identifier 36 | /// Operation type 37 | /// Email (only for subscriptions) 38 | /// Product identifier (for product attributes, attribute values and attribute combinations) 39 | Task CreateOrUpdateRecordAsync(EntityType entityType, int entityId, OperationType operationType, string email = null, int productId = 0); 40 | 41 | /// 42 | /// Insert a synchronization record 43 | /// 44 | /// Synchronization record 45 | Task InsertRecordAsync(MailChimpSynchronizationRecord record); 46 | 47 | /// 48 | /// Update a synchronization record 49 | /// 50 | /// Synchronization record 51 | Task UpdateRecordAsync(MailChimpSynchronizationRecord record); 52 | 53 | /// 54 | /// Delete a synchronization record 55 | /// 56 | /// Synchronization record 57 | Task DeleteRecordAsync(MailChimpSynchronizationRecord record); 58 | 59 | /// 60 | /// Delete synchronization records by entity type 61 | /// 62 | /// Entity type 63 | Task DeleteRecordsByEntityTypeAsync(EntityType entityType); 64 | 65 | /// 66 | /// Delete all synchronization records 67 | /// 68 | Task ClearRecordsAsync(); 69 | } -------------------------------------------------------------------------------- /Nop.Plugin.Misc.MailChimp/Services/MailChimpManager.cs: -------------------------------------------------------------------------------- 1 | using MailChimp.Net.Core; 2 | using MailChimp.Net.Interfaces; 3 | using Microsoft.AspNetCore.Http; 4 | using Microsoft.AspNetCore.Mvc; 5 | using Microsoft.AspNetCore.Mvc.Infrastructure; 6 | using Microsoft.AspNetCore.Mvc.Rendering; 7 | using Microsoft.AspNetCore.Mvc.Routing; 8 | using Microsoft.Net.Http.Headers; 9 | using Newtonsoft.Json; 10 | using Nop.Core; 11 | using Nop.Core.Domain.Catalog; 12 | using Nop.Core.Domain.Common; 13 | using Nop.Core.Domain.Customers; 14 | using Nop.Core.Domain.Directory; 15 | using Nop.Core.Domain.Messages; 16 | using Nop.Core.Domain.Orders; 17 | using Nop.Core.Domain.Stores; 18 | using Nop.Plugin.Misc.MailChimp.Domain; 19 | using Nop.Services.Catalog; 20 | using Nop.Services.Common; 21 | using Nop.Services.Configuration; 22 | using Nop.Services.Customers; 23 | using Nop.Services.Directory; 24 | using Nop.Services.Helpers; 25 | using Nop.Services.Html; 26 | using Nop.Services.Localization; 27 | using Nop.Services.Logging; 28 | using Nop.Services.Media; 29 | using Nop.Services.Messages; 30 | using Nop.Services.Orders; 31 | using Nop.Services.Seo; 32 | using Nop.Services.Stores; 33 | using SharpCompress.Readers; 34 | using System.Net; 35 | using System.Text; 36 | using Mailchimp = MailChimp.Net.Models; 37 | 38 | namespace Nop.Plugin.Misc.MailChimp.Services; 39 | 40 | /// 41 | /// Represents MailChimp manager 42 | /// 43 | public class MailChimpManager 44 | { 45 | #region Fields 46 | 47 | private readonly CurrencySettings _currencySettings; 48 | private readonly IActionContextAccessor _actionContextAccessor; 49 | private readonly IAddressService _addressService; 50 | private readonly ICategoryService _categoryService; 51 | private readonly ICountryService _countryService; 52 | private readonly ICurrencyService _currencyService; 53 | private readonly ICustomerService _customerService; 54 | private readonly IDateTimeHelper _dateTimeHelper; 55 | private readonly IGenericAttributeService _genericAttributeService; 56 | private readonly IHtmlFormatter _htmlFormatter; 57 | private readonly ILanguageService _languageService; 58 | private readonly ILogger _logger; 59 | private readonly IMailChimpManager _mailChimpManager; 60 | private readonly IManufacturerService _manufacturerService; 61 | private readonly INewsLetterSubscriptionService _newsLetterSubscriptionService; 62 | private readonly IOrderService _orderService; 63 | private readonly IPictureService _pictureService; 64 | private readonly IPriceCalculationService _priceCalculationService; 65 | private readonly IProductAttributeParser _productAttributeParser; 66 | private readonly IProductAttributeService _productAttributeService; 67 | private readonly IProductService _productService; 68 | private readonly ISettingService _settingService; 69 | private readonly IShoppingCartService _shoppingCartService; 70 | private readonly IStateProvinceService _stateProvinceService; 71 | private readonly IStoreMappingService _storeMappingService; 72 | private readonly IStoreService _storeService; 73 | private readonly ISynchronizationRecordService _synchronizationRecordService; 74 | private readonly IUrlHelperFactory _urlHelperFactory; 75 | private readonly IUrlRecordService _urlRecordService; 76 | private readonly IWebHelper _webHelper; 77 | private readonly IWorkContext _workContext; 78 | private readonly MailChimpSettings _mailChimpSettings; 79 | 80 | #endregion 81 | 82 | #region Ctor 83 | 84 | public MailChimpManager(CurrencySettings currencySettings, 85 | IActionContextAccessor actionContextAccessor, 86 | IAddressService addressService, 87 | ICategoryService categoryService, 88 | ICountryService countryService, 89 | ICurrencyService currencyService, 90 | ICustomerService customerService, 91 | IDateTimeHelper dateTimeHelper, 92 | IGenericAttributeService genericAttributeService, 93 | IHtmlFormatter htmlFormatter, 94 | ILanguageService languageService, 95 | ILogger logger, 96 | IManufacturerService manufacturerService, 97 | INewsLetterSubscriptionService newsLetterSubscriptionService, 98 | IOrderService orderService, 99 | IPictureService pictureService, 100 | IPriceCalculationService priceCalculationService, 101 | IProductAttributeParser productAttributeParser, 102 | IProductAttributeService productAttributeService, 103 | IProductService productService, 104 | ISettingService settingService, 105 | IShoppingCartService shoppingCartService, 106 | IStateProvinceService stateProvinceService, 107 | IStoreMappingService storeMappingService, 108 | IStoreService storeService, 109 | ISynchronizationRecordService synchronizationRecordService, 110 | IUrlHelperFactory urlHelperFactory, 111 | IUrlRecordService urlRecordService, 112 | IWebHelper webHelper, 113 | IWorkContext workContext, 114 | MailChimpSettings mailChimpSettings) 115 | { 116 | _currencySettings = currencySettings; 117 | _actionContextAccessor = actionContextAccessor; 118 | _addressService = addressService; 119 | _categoryService = categoryService; 120 | _countryService = countryService; 121 | _currencyService = currencyService; 122 | _customerService = customerService; 123 | _dateTimeHelper = dateTimeHelper; 124 | _languageService = languageService; 125 | _logger = logger; 126 | _manufacturerService = manufacturerService; 127 | _newsLetterSubscriptionService = newsLetterSubscriptionService; 128 | _orderService = orderService; 129 | _pictureService = pictureService; 130 | _priceCalculationService = priceCalculationService; 131 | _productAttributeParser = productAttributeParser; 132 | _productAttributeService = productAttributeService; 133 | _productService = productService; 134 | _settingService = settingService; 135 | _shoppingCartService = shoppingCartService; 136 | _stateProvinceService = stateProvinceService; 137 | _storeMappingService = storeMappingService; 138 | _storeService = storeService; 139 | _synchronizationRecordService = synchronizationRecordService; 140 | _urlHelperFactory = urlHelperFactory; 141 | _webHelper = webHelper; 142 | _workContext = workContext; 143 | _genericAttributeService = genericAttributeService; 144 | _htmlFormatter = htmlFormatter; 145 | _mailChimpSettings = mailChimpSettings; 146 | _urlRecordService = urlRecordService; 147 | 148 | //create wrapper MailChimp manager 149 | if (!string.IsNullOrEmpty(_mailChimpSettings.ApiKey)) 150 | _mailChimpManager = new global::MailChimp.Net.MailChimpManager(_mailChimpSettings.ApiKey); 151 | } 152 | 153 | #endregion 154 | 155 | #region Utilities 156 | 157 | /// 158 | /// Handle request 159 | /// 160 | /// Output type 161 | /// Request actions 162 | /// The asynchronous task whose result contains the object of T type 163 | private async Task HandleRequestAsync(Func> request) 164 | { 165 | try 166 | { 167 | //ensure that plugin is configured 168 | if (_mailChimpManager == null) 169 | throw new NopException("Plugin is not configured"); 170 | 171 | return await request(); 172 | } 173 | catch (Exception exception) 174 | { 175 | //compose an error message 176 | var errorMessage = exception.Message; 177 | if (exception is MailChimpException mailChimpException) 178 | { 179 | errorMessage = $"{mailChimpException.Status} {mailChimpException.Title} - {mailChimpException.Detail}{Environment.NewLine}"; 180 | if (mailChimpException.Errors?.Any() ?? false) 181 | { 182 | var errorDetails = mailChimpException.Errors 183 | .Aggregate(string.Empty, (error, detail) => $"{error}{detail?.Field} - {detail?.Message}{Environment.NewLine}"); 184 | errorMessage = $"{errorMessage} Errors: {errorDetails}"; 185 | } 186 | } 187 | 188 | //log errors 189 | await _logger.ErrorAsync($"MailChimp error. {errorMessage}", exception, await _workContext.GetCurrentCustomerAsync()); 190 | 191 | return default; 192 | } 193 | } 194 | 195 | #region Synchronization 196 | 197 | /// 198 | /// Prepare records for the manual synchronization 199 | /// 200 | /// The asynchronous task whose result determines whether the records prepared 201 | private async Task PrepareRecordsToManualSynchronizationAsync() 202 | { 203 | return await HandleRequestAsync(async () => 204 | { 205 | //whether to clear existing E-Commerce data 206 | if (_mailChimpSettings.PassEcommerceData) 207 | { 208 | //get store identifiers 209 | var allStoresIds = (await _storeService.GetAllStoresAsync()).Select(store => string.Format(_mailChimpSettings.StoreIdMask, store.Id)); 210 | 211 | //get number of stores 212 | var storeNumber = (await _mailChimpManager.ECommerceStores.GetResponseAsync())?.TotalItems 213 | ?? throw new NopException("No response from the service"); 214 | 215 | //delete all existing E-Commerce data from MailChimp 216 | var existingStoresIds = await _mailChimpManager.ECommerceStores 217 | .GetAllAsync(new QueryableBaseRequest { FieldsToInclude = "stores.id", Limit = storeNumber }) 218 | ?? throw new NopException("No response from the service"); 219 | foreach (var storeId in existingStoresIds.Select(store => store.Id).Intersect(allStoresIds)) 220 | { 221 | await _mailChimpManager.ECommerceStores.DeleteAsync(storeId); 222 | } 223 | 224 | //clear records 225 | await _synchronizationRecordService.ClearRecordsAsync(); 226 | 227 | } 228 | else 229 | await _synchronizationRecordService.DeleteRecordsByEntityTypeAsync(EntityType.Subscription); 230 | 231 | //and create initial data 232 | await CreateInitialDataAsync(); 233 | 234 | return true; 235 | }); 236 | } 237 | 238 | /// 239 | /// Create data for the manual synchronization 240 | /// 241 | /// A task that represents the asynchronous operation 242 | private async Task CreateInitialDataAsync() 243 | { 244 | //add all subscriptions 245 | var allSubscriptions = await _newsLetterSubscriptionService.GetAllNewsLetterSubscriptionsAsync(); 246 | if (!_mailChimpSettings.PassEcommerceData && !allSubscriptions.Any()) 247 | throw new NopException("No newsletter subscriptions found"); 248 | 249 | foreach (var subscription in allSubscriptions) 250 | { 251 | await _synchronizationRecordService.InsertRecordAsync(new MailChimpSynchronizationRecord 252 | { 253 | EntityType = EntityType.Subscription, 254 | EntityId = subscription.Id, 255 | OperationType = OperationType.Create 256 | }); 257 | } 258 | 259 | //check whether to pass E-Commerce data 260 | if (!_mailChimpSettings.PassEcommerceData) 261 | return; 262 | 263 | //add stores 264 | foreach (var store in await _storeService.GetAllStoresAsync()) 265 | { 266 | await _synchronizationRecordService.InsertRecordAsync(new MailChimpSynchronizationRecord 267 | { 268 | EntityType = EntityType.Store, 269 | EntityId = store.Id, 270 | OperationType = OperationType.Create 271 | }); 272 | } 273 | 274 | if (!_mailChimpSettings.PassOnlySubscribed) 275 | { 276 | var customers = await (await _customerService.GetAllCustomersAsync()) 277 | .WhereAwait(async customer => !await _customerService.IsGuestAsync(customer)) 278 | .ToListAsync(); 279 | 280 | 281 | //add registered customers 282 | foreach (var customer in customers) 283 | { 284 | await _synchronizationRecordService.InsertRecordAsync(new MailChimpSynchronizationRecord 285 | { 286 | EntityType = EntityType.Customer, 287 | EntityId = customer.Id, 288 | OperationType = OperationType.Create 289 | }); 290 | } 291 | } 292 | 293 | //add products 294 | foreach (var product in await _productService.SearchProductsAsync()) 295 | { 296 | await _synchronizationRecordService.InsertRecordAsync(new MailChimpSynchronizationRecord 297 | { 298 | EntityType = EntityType.Product, 299 | EntityId = product.Id, 300 | OperationType = OperationType.Create 301 | }); 302 | } 303 | 304 | //add orders 305 | foreach (var order in await _orderService.SearchOrdersAsync()) 306 | { 307 | await _synchronizationRecordService.InsertRecordAsync(new MailChimpSynchronizationRecord 308 | { 309 | EntityType = EntityType.Order, 310 | EntityId = order.Id, 311 | OperationType = OperationType.Create 312 | }); 313 | } 314 | } 315 | 316 | /// 317 | /// Prepare batch webhook before the synchronization 318 | /// 319 | /// The asynchronous task whose result determines whether the batch webhook prepared 320 | private async Task PrepareBatchWebhookAsync() 321 | { 322 | return await HandleRequestAsync(async () => 323 | { 324 | //get all batch webhooks 325 | var allBatchWebhooks = await _mailChimpManager.BatchWebHooks.GetAllAsync(new QueryableBaseRequest { Limit = int.MaxValue }) 326 | ?? throw new NopException("No response from the service"); 327 | 328 | //generate webhook URL 329 | var webhookUrl = _urlHelperFactory.GetUrlHelper(_actionContextAccessor.ActionContext) 330 | .RouteUrl(MailChimpDefaults.BatchWebhookRoute, null, _actionContextAccessor.ActionContext.HttpContext.Request.Scheme); 331 | 332 | //create the new one if not exists 333 | var batchWebhook = allBatchWebhooks.FirstOrDefault(webhook => !string.IsNullOrEmpty(webhook.Url) && webhook.Url.Equals(webhookUrl, StringComparison.InvariantCultureIgnoreCase)); 334 | if (string.IsNullOrEmpty(batchWebhook?.Id)) 335 | { 336 | batchWebhook = await _mailChimpManager.BatchWebHooks.AddAsync(webhookUrl) 337 | ?? throw new NopException("No response from the service"); 338 | } 339 | 340 | return !string.IsNullOrEmpty(batchWebhook.Id); 341 | }); 342 | } 343 | 344 | /// 345 | /// Create operation to manage MailChimp data 346 | /// 347 | /// Type of object value 348 | /// Object value 349 | /// Operation type 350 | /// Path of API request 351 | /// Operation ID 352 | /// Additional parameters 353 | /// Operation 354 | private Operation CreateOperation(T objectValue, OperationType operationType, 355 | string requestPath, string operationId, object additionalData = null) 356 | { 357 | return new Operation 358 | { 359 | Method = GetWebMethod(operationType), 360 | OperationId = operationId, 361 | Path = requestPath, 362 | Body = JsonConvert.SerializeObject(objectValue, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }), 363 | Params = additionalData, 364 | }; 365 | } 366 | 367 | /// 368 | /// Get web request method for the passed operation type 369 | /// 370 | /// Operation type 371 | /// Method name 372 | private string GetWebMethod(OperationType operationType) 373 | { 374 | return operationType switch 375 | { 376 | OperationType.Read => WebRequestMethods.Http.Get, 377 | OperationType.Create => WebRequestMethods.Http.Post, 378 | OperationType.Update => MailChimpDefaults.PatchRequestMethod, 379 | OperationType.Delete => MailChimpDefaults.DeleteRequestMethod, 380 | OperationType.CreateOrUpdate => WebRequestMethods.Http.Put, 381 | _ => WebRequestMethods.Http.Get, 382 | }; 383 | } 384 | 385 | /// 386 | /// Log result of the synchronization 387 | /// 388 | /// Batch identifier 389 | /// The asynchronous task whose result contains number of completed operations 390 | private async Task LogSynchronizationResultAsync(string batchId) 391 | { 392 | return await HandleRequestAsync(async () => 393 | { 394 | //try to get finished batch of operations 395 | var batch = await _mailChimpManager.Batches.GetBatchStatus(batchId) 396 | ?? throw new NopException("No response from the service"); 397 | 398 | var completeStatus = "finished"; 399 | if (!batch?.Status?.Equals(completeStatus) ?? true) 400 | return null; 401 | 402 | var operationResults = new List(); 403 | if (!string.IsNullOrEmpty(batch.ResponseBodyUrl)) 404 | { 405 | //get additional result info from MailChimp servers 406 | using var httpClient = new HttpClient(); 407 | 408 | //configure client 409 | httpClient.Timeout = TimeSpan.FromSeconds(20); 410 | httpClient.DefaultRequestHeaders.Add(HeaderNames.UserAgent, $"nopCommerce-{NopVersion.CURRENT_VERSION}"); 411 | var response = await httpClient.GetAsync(batch.ResponseBodyUrl); 412 | 413 | response.EnsureSuccessStatusCode(); 414 | using var stream = await response.Content.ReadAsStreamAsync(); 415 | 416 | //operation results represent a gzipped tar archive of JSON files, so extract it 417 | using var archiveReader = ReaderFactory.Open(stream); 418 | while (archiveReader.MoveToNextEntry()) 419 | { 420 | if (!archiveReader.Entry.IsDirectory) 421 | { 422 | using var unzippedEntryStream = archiveReader.OpenEntryStream(); 423 | using var entryReader = new StreamReader(unzippedEntryStream); 424 | var entryText = entryReader.ReadToEnd(); 425 | operationResults.AddRange(JsonConvert.DeserializeObject>(entryText)); 426 | } 427 | } 428 | } 429 | 430 | //log info 431 | var message = new StringBuilder(); 432 | message.AppendLine("MailChimp info."); 433 | message.AppendLine($"Synchronization started at: {batch.SubmittedAt}"); 434 | message.AppendLine($"completed at: {batch.CompletedAt}"); 435 | message.AppendLine($"finished operations: {batch.FinishedOperations}"); 436 | message.AppendLine($"errored operations: {batch.ErroredOperations}"); 437 | message.AppendLine($"total operations: {batch.TotalOperations}"); 438 | message.AppendLine($"batch ID: {batch.Id}"); 439 | message.AppendLine($"batch status: {batch.Status}"); 440 | 441 | //whether there are errors in operation results 442 | var operationResultsWithErrors = operationResults 443 | .Where(result => !int.TryParse(result.StatusCode, out var statusCode) || statusCode != (int)HttpStatusCode.OK); 444 | if (operationResultsWithErrors.Any()) 445 | { 446 | message.AppendLine("Synchronization errors:"); 447 | foreach (var operationResult in operationResultsWithErrors) 448 | { 449 | var errorInfo = JsonConvert.DeserializeObject(operationResult.ResponseString, new JsonSerializerSettings 450 | { 451 | Error = (sender, args) => { args.ErrorContext.Handled = true; } 452 | }); 453 | 454 | var errorMessage = $"Operation {operationResult.OperationId}"; 455 | if (errorInfo.Errors?.Any() ?? false) 456 | { 457 | var errorDetails = errorInfo.Errors 458 | .Aggregate(string.Empty, (error, detail) => $"{error}{detail?.Field} - {detail?.Message};"); 459 | errorMessage = $"{errorInfo.Type} - {errorInfo.Title} - {errorMessage} - {errorDetails}"; 460 | } 461 | else 462 | errorMessage = $"{errorInfo.Type} - {errorInfo.Title} - {errorMessage} - {errorInfo.Detail}"; 463 | 464 | message.AppendLine(errorMessage); 465 | } 466 | } 467 | 468 | await _logger.InformationAsync(message.ToString()); 469 | 470 | return batch.TotalOperations; 471 | }); 472 | } 473 | 474 | #region Subscriptions 475 | 476 | /// 477 | /// Get operations to manage subscriptions 478 | /// 479 | /// 480 | /// A task that represents the asynchronous operation 481 | /// The task result contains the list of operation 482 | /// 483 | private async Task> GetSubscriptionsOperationsAsync() 484 | { 485 | var operations = new List(); 486 | 487 | //prepare operations 488 | operations.AddRange(await GetCreateOrUpdateSubscriptionsOperationsAsync()); 489 | operations.AddRange(await GetDeleteSubscriptionsOperationsAsync()); 490 | 491 | return operations; 492 | } 493 | 494 | /// 495 | /// Get operations to create and update subscriptions 496 | /// 497 | /// 498 | /// A task that represents the asynchronous operation 499 | /// The task result contains the list of operation 500 | /// 501 | private async Task> GetCreateOrUpdateSubscriptionsOperationsAsync() 502 | { 503 | var operations = new List(); 504 | 505 | //get created and updated subscriptions 506 | var records = _synchronizationRecordService.GetRecordsByEntityTypeAndOperationType(EntityType.Subscription, OperationType.Create).ToList(); 507 | records.AddRange(_synchronizationRecordService.GetRecordsByEntityTypeAndOperationType(EntityType.Subscription, OperationType.Update)); 508 | var subscriptions = await records.Distinct().SelectAwait(async record => await _newsLetterSubscriptionService.GetNewsLetterSubscriptionByIdAsync(record.EntityId)).ToListAsync(); 509 | 510 | foreach (var store in await _storeService.GetAllStoresAsync()) 511 | { 512 | //try to get list ID for the store 513 | var listId = await _settingService 514 | .GetSettingByKeyAsync($"{nameof(MailChimpSettings)}.{nameof(MailChimpSettings.ListId)}", storeId: store.Id, loadSharedValueIfNotFound: true); 515 | if (string.IsNullOrEmpty(listId)) 516 | continue; 517 | 518 | //filter subscriptions by store 519 | var storeSubscriptions = subscriptions.Where(subscription => subscription?.StoreId == store.Id); 520 | 521 | foreach (var subscription in storeSubscriptions) 522 | { 523 | var member = await CreateMemberBySubscriptionAsync(subscription); 524 | if (member == null) 525 | continue; 526 | 527 | if (string.IsNullOrEmpty(subscription.Email)) 528 | continue; 529 | 530 | //create hash by email 531 | var hash = _mailChimpManager.Members.Hash(subscription.Email); 532 | 533 | //prepare request path and operation ID 534 | var requestPath = string.Format(MailChimpDefaults.MembersApiPath, listId, hash); 535 | var operationId = $"createOrUpdate-subscription-{subscription.Id}-list-{listId}"; 536 | 537 | //add operation 538 | operations.Add(CreateOperation(member, OperationType.CreateOrUpdate, requestPath, operationId)); 539 | } 540 | } 541 | 542 | return operations; 543 | } 544 | 545 | /// 546 | /// Get operations to delete subscriptions 547 | /// 548 | /// 549 | /// A task that represents the asynchronous operation 550 | /// The task result contains the list of operation 551 | /// 552 | private async Task> GetDeleteSubscriptionsOperationsAsync() 553 | { 554 | var operations = new List(); 555 | 556 | //ge records of deleted subscriptions 557 | var records = _synchronizationRecordService.GetRecordsByEntityTypeAndOperationType(EntityType.Subscription, OperationType.Delete); 558 | 559 | foreach (var store in await _storeService.GetAllStoresAsync()) 560 | { 561 | //try to get list ID for the store 562 | var listId = await _settingService 563 | .GetSettingByKeyAsync($"{nameof(MailChimpSettings)}.{nameof(MailChimpSettings.ListId)}", storeId: store.Id, loadSharedValueIfNotFound: true); 564 | if (string.IsNullOrEmpty(listId)) 565 | continue; 566 | 567 | foreach (var record in records) 568 | { 569 | //if subscription still exist, don't delete it from MailChimp 570 | var subscription = await _newsLetterSubscriptionService.GetNewsLetterSubscriptionByEmailAndStoreIdAsync(record.Email, store.Id); 571 | if (subscription != null) 572 | continue; 573 | 574 | if (string.IsNullOrEmpty(record.Email)) 575 | continue; 576 | 577 | //create hash by email 578 | var hash = _mailChimpManager.Members.Hash(record.Email); 579 | 580 | //prepare request path and operation ID 581 | var requestPath = string.Format(MailChimpDefaults.MembersApiPath, listId, hash); 582 | var operationId = $"delete-subscription-{record.EntityId}-list-{listId}"; 583 | 584 | //add operation 585 | operations.Add(CreateOperation(null, OperationType.Delete, requestPath, operationId)); 586 | } 587 | } 588 | 589 | return operations; 590 | } 591 | 592 | /// 593 | /// Create MailChimp member object by nopCommerce newsletter subscription object 594 | /// 595 | /// Newsletter subscription 596 | /// 597 | /// A task that represents the asynchronous operation 598 | /// The task result contains the Member 599 | /// 600 | private async Task CreateMemberBySubscriptionAsync(NewsLetterSubscription subscription) 601 | { 602 | //whether email exists 603 | if (string.IsNullOrEmpty(subscription?.Email)) 604 | return null; 605 | 606 | var member = new Mailchimp.Member 607 | { 608 | EmailAddress = subscription.Email, 609 | TimestampSignup = subscription.CreatedOnUtc.ToString("yyyy-MM-ddTHH:mm:ssZ") 610 | }; 611 | 612 | //set member status 613 | var status = subscription.Active ? Mailchimp.Status.Subscribed : Mailchimp.Status.Unsubscribed; 614 | member.Status = status; 615 | member.StatusIfNew = status; 616 | 617 | //if a customer of the subscription isn't a guest, add some specific properties 618 | var customer = await _customerService.GetCustomerByEmailAsync(subscription.Email); 619 | if (customer != null && !await _customerService.IsGuestAsync(customer)) 620 | { 621 | //try to add language 622 | var languageId = customer.LanguageId ?? 0; 623 | if (languageId > 0) 624 | member.Language = (await _languageService.GetLanguageByIdAsync(languageId))?.UniqueSeoCode; 625 | 626 | //try to add names 627 | var firstName = customer.FirstName; 628 | var lastName = customer.LastName; 629 | if (!string.IsNullOrEmpty(firstName) || !string.IsNullOrEmpty(lastName)) 630 | { 631 | member.MergeFields = new Dictionary 632 | { 633 | [MailChimpDefaults.FirstNameMergeField] = firstName, 634 | [MailChimpDefaults.LastNameMergeField] = lastName 635 | }; 636 | } 637 | } 638 | 639 | return member; 640 | } 641 | 642 | #endregion 643 | 644 | #region E-Commerce data 645 | 646 | /// 647 | /// Get operations to manage E-Commerce data 648 | /// 649 | /// The asynchronous task whose result contains the list of operations 650 | private async Task> GetEcommerceApiOperationsAsync() 651 | { 652 | var operations = new List(); 653 | 654 | //prepare operations 655 | operations.AddRange(await GetStoreOperationsAsync()); 656 | operations.AddRange(await GetCustomerOperationsAsync()); 657 | operations.AddRange(await GetProductOperationsAsync()); 658 | operations.AddRange(await GetProductVariantOperationsAsync()); 659 | operations.AddRange(await GetOrderOperationsAsync()); 660 | operations.AddRange(await GetCartOperationsAsync()); 661 | 662 | return operations; 663 | } 664 | 665 | /// 666 | /// Get code of the primary store currency 667 | /// 668 | /// 669 | /// A task that represents the asynchronous operation 670 | /// The task result contains the CurrencyCode 671 | /// 672 | private async Task GetCurrencyCodeAsync() 673 | { 674 | var currencyCode = (await _currencyService.GetCurrencyByIdAsync(_currencySettings.PrimaryStoreCurrencyId))?.CurrencyCode; 675 | if (!Enum.TryParse(currencyCode, true, out CurrencyCode result)) 676 | result = CurrencyCode.USD; 677 | 678 | return result; 679 | } 680 | 681 | #region Stores 682 | 683 | /// 684 | /// Get operations to manage stores 685 | /// 686 | /// The asynchronous task whose result contains the list of operations 687 | private async Task> GetStoreOperationsAsync() 688 | { 689 | //first create stores, we don't use batch operations, coz the store is the root object for all E-Commerce data 690 | //and we need to make sure that it is created 691 | await CreateStoresAsync(); 692 | 693 | var operations = new List(); 694 | 695 | //prepare operations 696 | operations.AddRange(await GetUpdateStoresOperationsAsync()); 697 | operations.AddRange(GetDeleteStoresOperations()); 698 | 699 | return operations; 700 | } 701 | 702 | /// 703 | /// Create stores 704 | /// 705 | /// The asynchronous task whose result determines whether stores successfully created 706 | private async Task CreateStoresAsync() 707 | { 708 | return await HandleRequestAsync(async () => 709 | { 710 | //get created stores 711 | var records = _synchronizationRecordService.GetRecordsByEntityTypeAndOperationType(EntityType.Store, OperationType.Create); 712 | var stores = await records.SelectAwait(async record => await _storeService.GetStoreByIdAsync(record.EntityId)).ToListAsync(); 713 | 714 | foreach (var store in stores) 715 | { 716 | var storeObject = await MapStoreAsync(store); 717 | if (storeObject == null) 718 | continue; 719 | 720 | //create store 721 | await HandleRequestAsync(async () => await _mailChimpManager.ECommerceStores.AddAsync(storeObject)); 722 | } 723 | 724 | return true; 725 | }); 726 | } 727 | 728 | /// 729 | /// Get operations to update stores 730 | /// 731 | /// The asynchronous task whose result contains the list of operations 732 | private async Task> GetUpdateStoresOperationsAsync() 733 | { 734 | var operations = new List(); 735 | 736 | //get updated stores 737 | var records = _synchronizationRecordService.GetRecordsByEntityTypeAndOperationType(EntityType.Store, OperationType.Update); 738 | var stores = await records.SelectAwait(async record => await _storeService.GetStoreByIdAsync(record.EntityId)).ToListAsync(); 739 | 740 | foreach (var store in stores) 741 | { 742 | var storeObject = await MapStoreAsync(store); 743 | if (storeObject == null) 744 | continue; 745 | 746 | //prepare request path and operation ID 747 | var storeId = string.Format(_mailChimpSettings.StoreIdMask, store.Id); 748 | var requestPath = string.Format(MailChimpDefaults.StoresApiPath, storeId); 749 | var operationId = $"update-store-{store.Id}"; 750 | 751 | //add operation 752 | operations.Add(CreateOperation(storeObject, OperationType.Update, requestPath, operationId)); 753 | } 754 | 755 | return operations; 756 | } 757 | 758 | /// 759 | /// Get operations to delete stores 760 | /// 761 | /// The asynchronous task whose result contains the list of operations 762 | private IEnumerable GetDeleteStoresOperations() 763 | { 764 | var operations = new List(); 765 | 766 | //get records of deleted stores 767 | var records = _synchronizationRecordService.GetRecordsByEntityTypeAndOperationType(EntityType.Store, OperationType.Delete); 768 | 769 | //add operations 770 | operations.AddRange(records.Select(record => 771 | { 772 | //prepare request path and operation ID 773 | var storeId = string.Format(_mailChimpSettings.StoreIdMask, record.EntityId); 774 | var requestPath = string.Format(MailChimpDefaults.StoresApiPath, storeId); 775 | var operationId = $"delete-store-{record.EntityId}"; 776 | 777 | return CreateOperation(null, OperationType.Delete, requestPath, operationId); 778 | })); 779 | 780 | return operations; 781 | } 782 | 783 | /// 784 | /// Create MailChimp store object by nopCommerce store object 785 | /// 786 | /// Store 787 | /// 788 | /// A task that represents the asynchronous operation 789 | /// The task result contains the Store 790 | /// 791 | private async Task MapStoreAsync(Store store) 792 | { 793 | var key = $"{nameof(MailChimpSettings)}.{nameof(MailChimpSettings.ListId)}"; 794 | return store == null ? null : new Mailchimp.Store 795 | { 796 | Id = string.Format(_mailChimpSettings.StoreIdMask, store.Id), 797 | ListId = await _settingService.GetSettingByKeyAsync(key: key, storeId: store.Id, loadSharedValueIfNotFound: true), 798 | Name = store.Name, 799 | Domain = _webHelper.GetStoreLocation(), 800 | CurrencyCode = await GetCurrencyCodeAsync(), 801 | PrimaryLocale = (await _languageService.GetLanguageByIdAsync(store.DefaultLanguageId) ?? (await _languageService.GetAllLanguagesAsync()).FirstOrDefault())?.UniqueSeoCode, 802 | Phone = store.CompanyPhoneNumber, 803 | Timezone = _dateTimeHelper.DefaultStoreTimeZone?.StandardName 804 | }; 805 | } 806 | 807 | #endregion 808 | 809 | #region Customers 810 | 811 | /// 812 | /// Get operations to manage customers 813 | /// 814 | /// List of operations 815 | private async Task> GetCustomerOperationsAsync() 816 | { 817 | var operations = new List(); 818 | 819 | //prepare operations 820 | operations.AddRange(await GetCreateOrUpdateCustomersOperationsAsync()); 821 | operations.AddRange(await GetDeleteCustomersOperationsAsync()); 822 | 823 | return operations; 824 | } 825 | 826 | /// 827 | /// Get operations to create and update customers 828 | /// 829 | /// List of operations 830 | private async Task> GetCreateOrUpdateCustomersOperationsAsync() 831 | { 832 | var operations = new List(); 833 | 834 | //get created and updated customers 835 | var records = _synchronizationRecordService.GetRecordsByEntityTypeAndOperationType(EntityType.Customer, OperationType.Create).ToList(); 836 | records.AddRange(_synchronizationRecordService.GetRecordsByEntityTypeAndOperationType(EntityType.Customer, OperationType.Update)); 837 | var customers = await _customerService.GetCustomersByIdsAsync(records.Select(record => record.EntityId).Distinct().ToArray()); 838 | 839 | foreach (var store in await _storeService.GetAllStoresAsync()) 840 | { 841 | //create customers for all stores 842 | foreach (var customer in customers) 843 | { 844 | var customerObject = await MapCustomerAsync(customer, store.Id); 845 | if (customerObject == null) 846 | continue; 847 | 848 | //prepare request path and operation ID 849 | var storeId = string.Format(_mailChimpSettings.StoreIdMask, store.Id); 850 | var requestPath = string.Format(MailChimpDefaults.CustomersApiPath, storeId, customer.Id); 851 | var operationId = $"createOrUpdate-customer-{customer.Id}-store-{store.Id}"; 852 | 853 | //add operation 854 | operations.Add(CreateOperation(customerObject, OperationType.CreateOrUpdate, requestPath, operationId)); 855 | } 856 | } 857 | 858 | return operations; 859 | } 860 | 861 | /// 862 | /// Get operations to delete customers 863 | /// 864 | /// List of operations 865 | private async Task> GetDeleteCustomersOperationsAsync() 866 | { 867 | var operations = new List(); 868 | 869 | //get records of deleted customers 870 | var records = _synchronizationRecordService.GetRecordsByEntityTypeAndOperationType(EntityType.Customer, OperationType.Delete); 871 | 872 | //add operations 873 | operations.AddRange((await _storeService.GetAllStoresAsync()).SelectMany(store => records.Select(record => 874 | { 875 | //prepare request path and operation ID 876 | var storeId = string.Format(_mailChimpSettings.StoreIdMask, store.Id); 877 | var requestPath = string.Format(MailChimpDefaults.CustomersApiPath, storeId, record.EntityId); 878 | var operationId = $"delete-customer-{record.EntityId}-store-{store.Id}"; 879 | 880 | return CreateOperation(null, OperationType.Delete, requestPath, operationId); 881 | }))); 882 | 883 | return operations; 884 | } 885 | 886 | /// 887 | /// Create MailChimp customer object by nopCommerce customer object 888 | /// 889 | /// Customer 890 | /// Store identifier 891 | /// Customer 892 | private async Task MapCustomerAsync(Customer customer, int storeId) 893 | { 894 | if (customer == null) 895 | return null; 896 | 897 | //get all customer orders 898 | var customerOrders = (await _orderService.SearchOrdersAsync(storeId: storeId, customerId: customer.Id)).ToList(); 899 | 900 | //get customer country and region 901 | var country = await _countryService.GetCountryByIdAsync(customer.CountryId); 902 | var stateProvince = await _stateProvinceService.GetStateProvinceByIdAsync(customer.StateProvinceId); 903 | 904 | return new Mailchimp.Customer 905 | { 906 | Id = customer.Id.ToString(), 907 | EmailAddress = customer.Email, 908 | OptInStatus = false, 909 | OrdersCount = customerOrders.Count, 910 | TotalSpent = customerOrders.Sum(order => order.OrderTotal), 911 | FirstName = customer.FirstName, 912 | LastName = customer.LastName, 913 | Company = customer.Company, 914 | Address = new Mailchimp.Address 915 | { 916 | Address1 = customer.StreetAddress, 917 | Address2 = customer.StreetAddress2, 918 | City = customer.City, 919 | Province = stateProvince?.Name, 920 | ProvinceCode = stateProvince?.Abbreviation, 921 | Country = country?.Name, 922 | CountryCode = country?.TwoLetterIsoCode, 923 | PostalCode = customer.ZipPostalCode 924 | } 925 | }; 926 | } 927 | 928 | #endregion 929 | 930 | #region Products 931 | 932 | /// 933 | /// Get operations to manage products 934 | /// 935 | /// List of operations 936 | private async Task> GetProductOperationsAsync() 937 | { 938 | var operations = new List(); 939 | 940 | //prepare operations 941 | operations.AddRange(await GetCreateProductsOperationsAsync()); 942 | operations.AddRange(await GetUpdateProductsOperationsAsync()); 943 | operations.AddRange(await GetDeleteProductsOperationsAsync()); 944 | 945 | return operations; 946 | } 947 | 948 | /// 949 | /// Get operations to create products 950 | /// 951 | /// List of operations 952 | private async Task> GetCreateProductsOperationsAsync() 953 | { 954 | var operations = new List(); 955 | 956 | //get created products 957 | var records = _synchronizationRecordService.GetRecordsByEntityTypeAndOperationType(EntityType.Product, OperationType.Create); 958 | var products = await _productService.GetProductsByIdsAsync(records.Select(record => record.EntityId).ToArray()); 959 | 960 | foreach (var store in await _storeService.GetAllStoresAsync()) 961 | { 962 | //filter products by the store 963 | var storeProducts = await products.WhereAwait(async product => await _storeMappingService.AuthorizeAsync(product, store.Id)).ToListAsync(); 964 | 965 | foreach (var product in storeProducts) 966 | { 967 | var productObject = await MapProductAsync(product); 968 | if (productObject == null) 969 | continue; 970 | 971 | //prepare request path and operation ID 972 | var storeId = string.Format(_mailChimpSettings.StoreIdMask, store.Id); 973 | var requestPath = string.Format(MailChimpDefaults.ProductsApiPath, storeId, string.Empty); 974 | var operationId = $"create-product-{product.Id}-store-{store.Id}"; 975 | 976 | //add operation 977 | operations.Add(CreateOperation(productObject, OperationType.Create, requestPath, operationId)); 978 | } 979 | } 980 | 981 | return operations; 982 | } 983 | 984 | /// 985 | /// Get operations to update products 986 | /// 987 | /// List of operations 988 | private async Task> GetUpdateProductsOperationsAsync() 989 | { 990 | var operations = new List(); 991 | 992 | //get updated products 993 | var records = _synchronizationRecordService.GetRecordsByEntityTypeAndOperationType(EntityType.Product, OperationType.Update); 994 | var products = await _productService.GetProductsByIdsAsync(records.Select(record => record.EntityId).ToArray()); 995 | 996 | foreach (var store in await _storeService.GetAllStoresAsync()) 997 | { 998 | //filter products by the store 999 | var storeProducts = await products.WhereAwait(async product => await _storeMappingService.AuthorizeAsync(product, store.Id)).ToListAsync(); 1000 | 1001 | foreach (var product in storeProducts) 1002 | { 1003 | var productObject = await MapProductAsync(product); 1004 | if (productObject == null) 1005 | continue; 1006 | 1007 | //prepare request path and operation ID 1008 | var storeId = string.Format(_mailChimpSettings.StoreIdMask, store.Id); 1009 | var requestPath = string.Format(MailChimpDefaults.ProductsApiPath, storeId, product.Id); 1010 | var operationId = $"update-product-{product.Id}-store-{store.Id}"; 1011 | 1012 | //add operation 1013 | operations.Add(CreateOperation(productObject, OperationType.Update, requestPath, operationId)); 1014 | 1015 | //add operation to update default product variant 1016 | var productVariant = await CreateDefaultProductVariantByProductAsync(product); 1017 | if (productVariant == null) 1018 | continue; 1019 | 1020 | var requestPathVariant = string.Format(MailChimpDefaults.ProductVariantsApiPath, storeId, product.Id, Guid.Empty.ToString()); 1021 | var operationIdVariant = $"update-productVariant-{Guid.Empty}-product-{product.Id}-store-{store.Id}"; 1022 | operations.Add(CreateOperation(productVariant, OperationType.Update, requestPathVariant, operationIdVariant)); 1023 | } 1024 | } 1025 | 1026 | return operations; 1027 | } 1028 | 1029 | /// 1030 | /// Get operations to delete products 1031 | /// 1032 | /// List of operations 1033 | private async Task> GetDeleteProductsOperationsAsync() 1034 | { 1035 | var operations = new List(); 1036 | 1037 | //get records of deleted products 1038 | var records = _synchronizationRecordService.GetRecordsByEntityTypeAndOperationType(EntityType.Product, OperationType.Delete); 1039 | 1040 | //add operations 1041 | operations.AddRange((await _storeService.GetAllStoresAsync()).SelectMany(store => records.Select(record => 1042 | { 1043 | //prepare request path and operation ID 1044 | var storeId = string.Format(_mailChimpSettings.StoreIdMask, store.Id); 1045 | var requestPath = string.Format(MailChimpDefaults.ProductsApiPath, storeId, record.EntityId); 1046 | var operationId = $"delete-product-{record.EntityId}-store-{store.Id}"; 1047 | 1048 | return CreateOperation(null, OperationType.Delete, requestPath, operationId); 1049 | }))); 1050 | 1051 | return operations; 1052 | } 1053 | 1054 | /// 1055 | /// Create MailChimp product object by nopCommerce product object 1056 | /// 1057 | /// Product 1058 | /// Product 1059 | private async Task MapProductAsync(Product product) 1060 | { 1061 | return product == null ? null : new Mailchimp.Product 1062 | { 1063 | Id = product.Id.ToString(), 1064 | Title = product.Name, 1065 | Url = _urlHelperFactory.GetUrlHelper(_actionContextAccessor.ActionContext) 1066 | .RouteUrl(nameof(Product), new { SeName = await _urlRecordService.GetSeNameAsync(product) }, _actionContextAccessor.ActionContext.HttpContext.Request.Scheme), 1067 | Description = _htmlFormatter.StripTags(!string.IsNullOrEmpty(product.FullDescription) ? product.FullDescription : 1068 | !string.IsNullOrEmpty(product.ShortDescription) ? product.ShortDescription : product.Name), 1069 | Type = (await _categoryService.GetCategoryByIdAsync((await _categoryService.GetProductCategoriesByProductIdAsync(product.Id)).FirstOrDefault()?.CategoryId ?? 0))?.Name, 1070 | Vendor = (await _manufacturerService.GetManufacturerByIdAsync((await _manufacturerService.GetProductManufacturersByProductIdAsync(product.Id))?.FirstOrDefault()?.ManufacturerId ?? 0))?.Name, 1071 | ImageUrl = await _pictureService.GetPictureUrlAsync((await _pictureService.GetProductPictureAsync(product, null))?.Id ?? 0), 1072 | Variants = await CreateProductVariantsByProductAsync(product) 1073 | }; 1074 | } 1075 | 1076 | /// 1077 | /// Create MailChimp product variant objects by nopCommerce product object 1078 | /// 1079 | /// Product 1080 | /// List of product variants 1081 | private async Task> CreateProductVariantsByProductAsync(Product product) 1082 | { 1083 | var variants = new List 1084 | { 1085 | //add default variant 1086 | await CreateDefaultProductVariantByProductAsync(product) 1087 | }; 1088 | 1089 | //add variants from attribute combinations 1090 | var combinationVariants = await (await _productAttributeService.GetAllProductAttributeCombinationsAsync(product.Id)) 1091 | .Where(combination => combination?.ProductId > 0) 1092 | .SelectAwait(async combination => await CreateProductVariantByAttributeCombinationAsync(combination)).ToListAsync(); 1093 | variants.AddRange(combinationVariants); 1094 | 1095 | return variants; 1096 | } 1097 | 1098 | /// 1099 | /// Create MailChimp product variant object by nopCommerce product object 1100 | /// 1101 | /// Product 1102 | /// Product variant 1103 | private async Task CreateDefaultProductVariantByProductAsync(Product product) 1104 | { 1105 | return product == null ? null : new Mailchimp.Variant 1106 | { 1107 | Id = Guid.Empty.ToString(), //set empty guid as identifier for default product variant 1108 | Title = product.Name, 1109 | Url = _urlHelperFactory.GetUrlHelper(_actionContextAccessor.ActionContext) 1110 | .RouteUrl(nameof(Product), new { SeName = await _urlRecordService.GetSeNameAsync(product) }, _actionContextAccessor.ActionContext.HttpContext.Request.Scheme), 1111 | Sku = product.Sku, 1112 | Price = product.Price, 1113 | ImageUrl = await _pictureService.GetPictureUrlAsync((await _pictureService.GetProductPictureAsync(product, null))?.Id ?? 0), 1114 | InventoryQuantity = product.ManageInventoryMethod != ManageInventoryMethod.DontManageStock ? product.StockQuantity : int.MaxValue, 1115 | Visibility = product.Published.ToString().ToLower() 1116 | }; 1117 | } 1118 | 1119 | /// 1120 | /// Create MailChimp product variant object by nopCommerce product attribute combination object 1121 | /// 1122 | /// Product attribute combination 1123 | /// Product variant 1124 | private async Task CreateProductVariantByAttributeCombinationAsync(ProductAttributeCombination combination) 1125 | { 1126 | if (combination?.ProductId == null || combination?.ProductId == 0) 1127 | return null; 1128 | 1129 | var product = await _productService.GetProductByIdAsync(combination.ProductId); 1130 | 1131 | return new Mailchimp.Variant 1132 | { 1133 | Id = combination.Id.ToString(), 1134 | Title = product.Name, 1135 | Url = _urlHelperFactory.GetUrlHelper(_actionContextAccessor.ActionContext).RouteUrl(nameof(Product), 1136 | new { SeName = await _urlRecordService.GetSeNameAsync(product) }, 1137 | _actionContextAccessor.ActionContext.HttpContext.Request.Scheme), 1138 | Sku = !string.IsNullOrEmpty(combination.Sku) ? combination.Sku : product.Sku, 1139 | Price = combination.OverriddenPrice ?? product.Price, 1140 | InventoryQuantity = product.ManageInventoryMethod == ManageInventoryMethod.ManageStockByAttributes 1141 | ? combination.StockQuantity : product.ManageInventoryMethod != ManageInventoryMethod.DontManageStock 1142 | ? product.StockQuantity : int.MaxValue, 1143 | ImageUrl = await _pictureService.GetPictureUrlAsync((await _pictureService.GetProductPictureAsync(product, combination.AttributesXml))?.Id ?? 0), 1144 | Visibility = product.Published.ToString().ToLowerInvariant() 1145 | }; 1146 | } 1147 | 1148 | /// 1149 | /// Get operations to manage product variants 1150 | /// 1151 | /// List of operations 1152 | private async Task> GetProductVariantOperationsAsync() 1153 | { 1154 | var operations = new List(); 1155 | 1156 | //prepare operations 1157 | operations.AddRange(await GetCreateOrUpdateProductVariantsOperationsAsync()); 1158 | operations.AddRange(await GetDeleteProductVariantsOperationsAsync()); 1159 | 1160 | return operations; 1161 | } 1162 | 1163 | /// 1164 | /// Get operations to create and update product variants 1165 | /// 1166 | /// List of operations 1167 | private async Task> GetCreateOrUpdateProductVariantsOperationsAsync() 1168 | { 1169 | var operations = new List(); 1170 | 1171 | //get created and updated product combinations 1172 | var records = _synchronizationRecordService.GetRecordsByEntityTypeAndOperationType(EntityType.AttributeCombination, OperationType.Create).ToList(); 1173 | records.AddRange(_synchronizationRecordService.GetRecordsByEntityTypeAndOperationType(EntityType.AttributeCombination, OperationType.Update)); 1174 | var combinations = await records.Distinct().SelectAwait(async record => await _productAttributeService.GetProductAttributeCombinationByIdAsync(record.EntityId)).ToListAsync(); 1175 | 1176 | foreach (var store in await _storeService.GetAllStoresAsync()) 1177 | { 1178 | //filter combinations by the store 1179 | var storeCombinations = await combinations.WhereAwait(async combination => 1180 | await _storeMappingService.AuthorizeAsync(await _productService.GetProductByIdAsync(combination.ProductId), store.Id)).ToListAsync(); 1181 | 1182 | foreach (var combination in storeCombinations) 1183 | { 1184 | var productVariant = await CreateProductVariantByAttributeCombinationAsync(combination); 1185 | if (productVariant == null) 1186 | continue; 1187 | 1188 | //prepare request path and operation ID 1189 | var storeId = string.Format(_mailChimpSettings.StoreIdMask, store.Id); 1190 | var requestPath = string.Format(MailChimpDefaults.ProductVariantsApiPath, storeId, combination.ProductId, combination.Id); 1191 | var operationId = $"createOrUpdate-productVariant-{combination.Id}-product-{combination.ProductId}-store-{store.Id}"; 1192 | 1193 | //add operation 1194 | operations.Add(CreateOperation(productVariant, OperationType.CreateOrUpdate, requestPath, operationId)); 1195 | } 1196 | } 1197 | 1198 | return operations; 1199 | } 1200 | 1201 | /// 1202 | /// Get operations to delete product variants 1203 | /// 1204 | /// List of operations 1205 | private async Task> GetDeleteProductVariantsOperationsAsync() 1206 | { 1207 | var operations = new List(); 1208 | 1209 | //get records of deleted product combinations 1210 | var records = _synchronizationRecordService.GetRecordsByEntityTypeAndOperationType(EntityType.AttributeCombination, OperationType.Delete); 1211 | 1212 | //add operations 1213 | operations.AddRange((await _storeService.GetAllStoresAsync()).SelectMany(store => records.Select(record => 1214 | { 1215 | //prepare request path and operation ID 1216 | var storeId = string.Format(_mailChimpSettings.StoreIdMask, store.Id); 1217 | var requestPath = string.Format(MailChimpDefaults.ProductVariantsApiPath, storeId, record.ProductId, record.EntityId); 1218 | var operationId = $"delete-productVariant-{record.EntityId}-product-{record.ProductId}-store-{store.Id}"; 1219 | 1220 | return CreateOperation(null, OperationType.Delete, requestPath, operationId); 1221 | }))); 1222 | 1223 | return operations; 1224 | } 1225 | 1226 | #endregion 1227 | 1228 | #region Orders 1229 | 1230 | /// 1231 | /// Get operations to manage orders 1232 | /// 1233 | /// List of operations 1234 | private async Task> GetOrderOperationsAsync() 1235 | { 1236 | var operations = new List(); 1237 | 1238 | //prepare operations 1239 | operations.AddRange(await GetCreateOrdersOperationsAsync()); 1240 | operations.AddRange(await GetUpdateOrdersOperationsAsync()); 1241 | operations.AddRange(await GetDeleteOrdersOperationsAsync()); 1242 | 1243 | return operations; 1244 | } 1245 | 1246 | /// 1247 | /// Get operations to create orders 1248 | /// 1249 | /// List of operations 1250 | private async Task> GetCreateOrdersOperationsAsync() 1251 | { 1252 | var operations = new List(); 1253 | 1254 | //get created orders 1255 | var records = _synchronizationRecordService.GetRecordsByEntityTypeAndOperationType(EntityType.Order, OperationType.Create); 1256 | var orders = await (await _orderService.GetOrdersByIdsAsync(records.Select(record => record.EntityId).ToArray())) 1257 | .WhereAwait(async order => !await _customerService.IsGuestAsync(await _customerService.GetCustomerByIdAsync(order.CustomerId))).ToListAsync(); 1258 | 1259 | foreach (var store in await _storeService.GetAllStoresAsync()) 1260 | { 1261 | //filter orders by the store 1262 | var storeOrders = orders.Where(order => order?.StoreId == store.Id); 1263 | 1264 | foreach (var order in storeOrders) 1265 | { 1266 | var orderObject = await MapOrderAsync(order); 1267 | if (orderObject == null) 1268 | continue; 1269 | 1270 | //prepare request path and operation ID 1271 | var storeId = string.Format(_mailChimpSettings.StoreIdMask, store.Id); 1272 | var requestPath = string.Format(MailChimpDefaults.OrdersApiPath, storeId, string.Empty); 1273 | var operationId = $"create-order-{order.Id}-store-{store.Id}"; 1274 | 1275 | //add operation 1276 | operations.Add(CreateOperation(orderObject, OperationType.Create, requestPath, operationId)); 1277 | } 1278 | } 1279 | 1280 | return operations; 1281 | } 1282 | 1283 | /// 1284 | /// Get operations to update orders 1285 | /// 1286 | /// List of operations 1287 | private async Task> GetUpdateOrdersOperationsAsync() 1288 | { 1289 | var operations = new List(); 1290 | 1291 | //get updated orders 1292 | var records = _synchronizationRecordService.GetRecordsByEntityTypeAndOperationType(EntityType.Order, OperationType.Update); 1293 | var orders = await (await _orderService.GetOrdersByIdsAsync(records.Select(record => record.EntityId).ToArray())) 1294 | .WhereAwait(async order => !await _customerService.IsGuestAsync(await _customerService.GetCustomerByIdAsync(order.CustomerId))).ToListAsync(); 1295 | 1296 | foreach (var store in await _storeService.GetAllStoresAsync()) 1297 | { 1298 | //filter orders by the store 1299 | var storeOrders = orders.Where(order => order?.StoreId == store.Id); 1300 | 1301 | foreach (var order in storeOrders) 1302 | { 1303 | var orderObject = await MapOrderAsync(order); 1304 | if (orderObject == null) 1305 | continue; 1306 | 1307 | //prepare request path and operation ID 1308 | var storeId = string.Format(_mailChimpSettings.StoreIdMask, store.Id); 1309 | var requestPath = string.Format(MailChimpDefaults.OrdersApiPath, storeId, order.Id); 1310 | var operationId = $"update-order-{order.Id}-store-{store.Id}"; 1311 | 1312 | //add operation 1313 | operations.Add(CreateOperation(orderObject, OperationType.Update, requestPath, operationId)); 1314 | } 1315 | } 1316 | 1317 | return operations; 1318 | } 1319 | 1320 | /// 1321 | /// Get operations to delete orders 1322 | /// 1323 | /// List of operations 1324 | private async Task> GetDeleteOrdersOperationsAsync() 1325 | { 1326 | var operations = new List(); 1327 | 1328 | //get records of deleted orders 1329 | var records = _synchronizationRecordService.GetRecordsByEntityTypeAndOperationType(EntityType.Order, OperationType.Delete); 1330 | 1331 | //add operations 1332 | operations.AddRange((await _storeService.GetAllStoresAsync()).SelectMany(store => records.Select(record => 1333 | { 1334 | //prepare request path and operation ID 1335 | var storeId = string.Format(_mailChimpSettings.StoreIdMask, store.Id); 1336 | var requestPath = string.Format(MailChimpDefaults.OrdersApiPath, storeId, record.EntityId); 1337 | var operationId = $"delete-order-{record.EntityId}-store-{store.Id}"; 1338 | 1339 | return CreateOperation(null, OperationType.Delete, requestPath, operationId); 1340 | }))); 1341 | 1342 | return operations; 1343 | } 1344 | 1345 | /// 1346 | /// Create MailChimp order object by nopCommerce order object 1347 | /// 1348 | /// Order 1349 | /// Order 1350 | private async Task MapOrderAsync(Order order) 1351 | { 1352 | return order == null ? null : new Mailchimp.Order 1353 | { 1354 | Id = order.Id.ToString(), 1355 | Customer = new Mailchimp.Customer { Id = order.CustomerId.ToString() }, 1356 | FinancialStatus = order.PaymentStatus.ToString("D"), 1357 | FulfillmentStatus = order.OrderStatus.ToString("D"), 1358 | CurrencyCode = await GetCurrencyCodeAsync(), 1359 | OrderTotal = order.OrderTotal, 1360 | TaxTotal = order.OrderTax, 1361 | ShippingTotal = order.OrderShippingInclTax, 1362 | ProcessedAtForeign = order.CreatedOnUtc.ToString("yyyy-MM-ddTHH:mm:ssZ"), 1363 | ShippingAddress = order.PickupInStore && order.PickupAddressId != null ? 1364 | await MapOrderAddressAsync(await _addressService.GetAddressByIdAsync(order.PickupAddressId ?? 0)) : 1365 | await MapOrderAddressAsync(await _addressService.GetAddressByIdAsync(order.ShippingAddressId ?? 0)), 1366 | BillingAddress = await MapOrderAddressAsync(await _addressService.GetAddressByIdAsync(order.BillingAddressId)), 1367 | Lines = await (await _orderService.GetOrderItemsAsync(order.Id)).SelectAwait(async item => await MapOrderItemAsync(item)).ToListAsync() 1368 | }; 1369 | } 1370 | 1371 | /// 1372 | /// Create MailChimp order address object by nopCommerce address object 1373 | /// 1374 | /// Address 1375 | /// Order address 1376 | private async Task MapOrderAddressAsync(Address address) 1377 | { 1378 | if (address == null) 1379 | return null; 1380 | 1381 | var stateProvince = await _stateProvinceService.GetStateProvinceByAddressAsync(address); 1382 | var country = await _countryService.GetCountryByAddressAsync(address); 1383 | 1384 | return new Mailchimp.OrderAddress 1385 | { 1386 | Phone = address.PhoneNumber, 1387 | Company = address.Company, 1388 | Address1 = address.Address1, 1389 | Address2 = address.Address2, 1390 | City = address.City, 1391 | Province = stateProvince?.Name, 1392 | ProvinceCode = stateProvince?.Abbreviation, 1393 | Country = country?.Name, 1394 | CountryCode = country?.TwoLetterIsoCode, 1395 | PostalCode = address.ZipPostalCode 1396 | }; 1397 | } 1398 | 1399 | /// 1400 | /// Create MailChimp line object by nopCommerce order item object 1401 | /// 1402 | /// Order item 1403 | /// Line 1404 | private async Task MapOrderItemAsync(OrderItem item) 1405 | { 1406 | var product = await _productService.GetProductByIdAsync(item?.ProductId ?? 0); 1407 | return product == null ? null : new Mailchimp.Line 1408 | { 1409 | Id = item.Id.ToString(), 1410 | ProductId = item.ProductId.ToString(), 1411 | ProductVariantId = (await _productAttributeParser 1412 | .FindProductAttributeCombinationAsync(product, item.AttributesXml))?.Id.ToString() ?? Guid.Empty.ToString(), 1413 | Price = item.PriceInclTax, 1414 | Quantity = item.Quantity 1415 | }; 1416 | } 1417 | 1418 | #endregion 1419 | 1420 | #region Carts 1421 | 1422 | /// 1423 | /// Get operations to manage carts 1424 | /// 1425 | /// The asynchronous task whose result contains the list of operations 1426 | private async Task> GetCartOperationsAsync() 1427 | { 1428 | var operations = new List(); 1429 | 1430 | //get customers with shopping cart 1431 | var customersWithCart = await (await _customerService.GetCustomersWithShoppingCartsAsync(ShoppingCartType.ShoppingCart)) 1432 | .WhereAwait(async customer => !await _customerService.IsGuestAsync(await _customerService.GetCustomerByIdAsync(customer.Id))).ToListAsync(); 1433 | 1434 | foreach (var store in await _storeService.GetAllStoresAsync()) 1435 | { 1436 | var storeId = string.Format(_mailChimpSettings.StoreIdMask, store.Id); 1437 | 1438 | //filter customers with cart by the store 1439 | var storeCustomersWithCart = await customersWithCart 1440 | .WhereAwait(async customer => (await _shoppingCartService.GetShoppingCartAsync(customer)).Any(cart => cart?.StoreId == store.Id)).ToListAsync(); 1441 | 1442 | //get existing carts on MailChimp 1443 | var cartsIds = await HandleRequestAsync(async () => 1444 | { 1445 | //get number of carts 1446 | var cartNumber = (await _mailChimpManager.ECommerceStores.Carts(storeId).GetResponseAsync())?.TotalItems 1447 | ?? throw new NopException("No response from the service"); 1448 | 1449 | return (await _mailChimpManager.ECommerceStores.Carts(storeId) 1450 | .GetAllAsync(new QueryableBaseRequest { FieldsToInclude = "carts.id", Limit = cartNumber })) 1451 | ?.Select(cart => cart.Id).ToList() 1452 | ?? throw new NopException("No response from the service"); 1453 | }) ?? new List(); 1454 | 1455 | //add operations to create carts 1456 | var newCustomersWithCart = storeCustomersWithCart.Where(customer => !cartsIds.Contains(customer.Id.ToString())); 1457 | foreach (var customer in newCustomersWithCart) 1458 | { 1459 | var cart = await CreateCartByCustomerAsync(customer, store.Id); 1460 | if (cart == null) 1461 | continue; 1462 | 1463 | //prepare request path and operation ID 1464 | var requestPath = string.Format(MailChimpDefaults.CartsApiPath, storeId, string.Empty); 1465 | var operationId = $"create-cart-{customer.Id}-store-{store.Id}"; 1466 | 1467 | //add operation 1468 | operations.Add(CreateOperation(cart, OperationType.Create, requestPath, operationId)); 1469 | } 1470 | 1471 | //add operations to update carts 1472 | var customersWithUpdatedCart = storeCustomersWithCart.Where(customer => cartsIds.Contains(customer.Id.ToString())); 1473 | foreach (var customer in customersWithUpdatedCart) 1474 | { 1475 | var cart = await CreateCartByCustomerAsync(customer, store.Id); 1476 | if (cart == null) 1477 | continue; 1478 | 1479 | //prepare request path and operation ID 1480 | var requestPath = string.Format(MailChimpDefaults.CartsApiPath, storeId, customer.Id); 1481 | var operationId = $"update-cart-{customer.Id}-store-{store.Id}"; 1482 | 1483 | //add operation 1484 | operations.Add(CreateOperation(cart, OperationType.Update, requestPath, operationId)); 1485 | } 1486 | 1487 | //add operations to delete carts 1488 | var customersIdsWithoutCart = cartsIds.Except(storeCustomersWithCart.Select(customer => customer.Id.ToString())); 1489 | operations.AddRange(customersIdsWithoutCart.Select(customerId => 1490 | { 1491 | //prepare request path and operation ID 1492 | var requestPath = string.Format(MailChimpDefaults.CartsApiPath, storeId, customerId); 1493 | var operationId = $"delete-cart-{customerId}-store-{store.Id}"; 1494 | 1495 | return CreateOperation(null, OperationType.Delete, requestPath, operationId); 1496 | })); 1497 | } 1498 | 1499 | return operations; 1500 | } 1501 | 1502 | /// 1503 | /// Create MailChimp cart object by nopCommerce customer object 1504 | /// 1505 | /// Customer 1506 | /// Store identifier 1507 | /// Cart 1508 | private async Task CreateCartByCustomerAsync(Customer customer, int storeId) 1509 | { 1510 | if (customer == null) 1511 | return null; 1512 | 1513 | //create cart lines 1514 | var lines = await (await _shoppingCartService.GetShoppingCartAsync(customer)) 1515 | .Where(cart => cart?.StoreId == storeId) 1516 | .SelectAwait(async item => await MapShoppingCartItemAsync(item)) 1517 | .Where(line => line != null).ToListAsync(); 1518 | 1519 | return new Mailchimp.Cart 1520 | { 1521 | Id = customer.Id.ToString(), 1522 | Customer = new Mailchimp.Customer { Id = customer.Id.ToString() }, 1523 | CheckoutUrl = _urlHelperFactory.GetUrlHelper(_actionContextAccessor.ActionContext) 1524 | .RouteUrl("ShoppingCart", null, _actionContextAccessor.ActionContext.HttpContext.Request.Scheme), 1525 | CurrencyCode = await GetCurrencyCodeAsync(), 1526 | OrderTotal = lines.Sum(line => line.Price), 1527 | Lines = lines 1528 | }; 1529 | } 1530 | 1531 | /// 1532 | /// Create MailChimp line object by nopCommerce shopping cart item object 1533 | /// 1534 | /// Shopping cart item 1535 | /// Line 1536 | private async Task MapShoppingCartItemAsync(ShoppingCartItem item) 1537 | { 1538 | var product = await _productService.GetProductByIdAsync(item.ProductId); 1539 | var (subTotal, _, _, _) = await _shoppingCartService.GetSubTotalAsync(item, true); 1540 | return item?.ProductId == null ? null : new Mailchimp.Line 1541 | { 1542 | Id = item.Id.ToString(), 1543 | ProductId = item.ProductId.ToString(), 1544 | ProductVariantId = (await _productAttributeParser.FindProductAttributeCombinationAsync(product, item.AttributesXml))?.Id.ToString() ?? Guid.Empty.ToString(), 1545 | Price = subTotal, 1546 | Quantity = item.Quantity 1547 | }; 1548 | } 1549 | 1550 | #endregion 1551 | 1552 | #endregion 1553 | 1554 | #endregion 1555 | 1556 | #endregion 1557 | 1558 | #region Methods 1559 | 1560 | /// 1561 | /// Synchronize data with MailChimp 1562 | /// 1563 | /// Whether it's a manual synchronization 1564 | /// The asynchronous task whose result contains number of operation to synchronize 1565 | public async Task SynchronizeAsync(bool manualSynchronization = false) 1566 | { 1567 | return await HandleRequestAsync(async () => 1568 | { 1569 | //prepare records to manual synchronization 1570 | if (manualSynchronization) 1571 | { 1572 | var recordsPrepared = await PrepareRecordsToManualSynchronizationAsync(); 1573 | if (!recordsPrepared) 1574 | return 0; 1575 | } 1576 | 1577 | //prepare batch webhook 1578 | var webhookPrepared = await PrepareBatchWebhookAsync(); 1579 | if (!webhookPrepared) 1580 | return 0; 1581 | 1582 | var operations = new List(); 1583 | 1584 | //preare subscription operations 1585 | operations.AddRange(await GetSubscriptionsOperationsAsync()); 1586 | 1587 | //prepare E-Commerce operations 1588 | if (_mailChimpSettings.PassEcommerceData) 1589 | operations.AddRange(await GetEcommerceApiOperationsAsync()); 1590 | 1591 | //start synchronization 1592 | var batchNumber = operations.Count / _mailChimpSettings.BatchOperationNumber + 1593 | (operations.Count % _mailChimpSettings.BatchOperationNumber > 0 ? 1 : 0); 1594 | for (var i = 0; i < batchNumber; i++) 1595 | { 1596 | var batchOperations = operations.Skip(i * _mailChimpSettings.BatchOperationNumber).Take(_mailChimpSettings.BatchOperationNumber); 1597 | _ = await _mailChimpManager.Batches.AddAsync(new BatchRequest { Operations = batchOperations }) 1598 | ?? throw new NopException("No response from the service"); 1599 | } 1600 | 1601 | //synchronization successfully started, thus delete records 1602 | if (_mailChimpSettings.PassEcommerceData) 1603 | await _synchronizationRecordService.ClearRecordsAsync(); 1604 | else 1605 | await _synchronizationRecordService.DeleteRecordsByEntityTypeAsync(EntityType.Subscription); 1606 | 1607 | return operations.Count; 1608 | }); 1609 | } 1610 | 1611 | /// 1612 | /// Get account information 1613 | /// 1614 | /// The asynchronous task whose result contains the account information 1615 | public async Task GetAccountInfoAsync() 1616 | { 1617 | return await HandleRequestAsync(async () => 1618 | { 1619 | //get account info 1620 | var apiInfo = await _mailChimpManager.Api.GetInfoAsync() 1621 | ?? throw new NopException("No response from the service"); 1622 | 1623 | return $"{apiInfo.AccountName}{Environment.NewLine}Total subscribers: {apiInfo.TotalSubscribers}"; 1624 | }); 1625 | } 1626 | 1627 | /// 1628 | /// Get available user lists for the synchronization 1629 | /// 1630 | /// The asynchronous task whose result contains the list of user lists 1631 | public async Task> GetAvailableListsAsync() 1632 | { 1633 | return await HandleRequestAsync(async () => 1634 | { 1635 | //get number of lists 1636 | var listNumber = (await _mailChimpManager.Lists.GetResponseAsync())?.TotalItems 1637 | ?? throw new NopException("No response from the service"); 1638 | 1639 | //get all available lists 1640 | var availableLists = await _mailChimpManager.Lists.GetAllAsync(new ListRequest { Limit = listNumber }) 1641 | ?? throw new NopException("No response from the service"); 1642 | 1643 | return availableLists.Select(list => new SelectListItem { Text = list.Name, Value = list.Id }).ToList(); 1644 | }); 1645 | } 1646 | 1647 | /// 1648 | /// Prepare webhook for passed list 1649 | /// 1650 | /// Current selected list identifier 1651 | /// The asynchronous task whose result determines whether webhook prepared 1652 | public async Task PrepareWebhookAsync(string listId) 1653 | { 1654 | return await HandleRequestAsync(async () => 1655 | { 1656 | //if list ID is empty, nothing to do 1657 | if (string.IsNullOrEmpty(listId)) 1658 | return true; 1659 | 1660 | //generate webhook URL 1661 | var webhookUrl = _urlHelperFactory.GetUrlHelper(_actionContextAccessor.ActionContext) 1662 | .RouteUrl(MailChimpDefaults.WebhookRoute, null, _actionContextAccessor.ActionContext.HttpContext.Request.Scheme); 1663 | 1664 | //get current list webhooks 1665 | var listWebhooks = await _mailChimpManager.WebHooks.GetAllAsync(listId) 1666 | ?? throw new NopException("No response from the service"); 1667 | 1668 | //create the new one if not exists 1669 | var listWebhook = listWebhooks 1670 | .FirstOrDefault(webhook => !string.IsNullOrEmpty(webhook.Url) && webhook.Url.Equals(webhookUrl, StringComparison.InvariantCultureIgnoreCase)); 1671 | if (string.IsNullOrEmpty(listWebhook?.Id)) 1672 | { 1673 | listWebhook = await _mailChimpManager.WebHooks.AddAsync(listId, new Mailchimp.WebHook 1674 | { 1675 | Event = new Mailchimp.Event { Subscribe = true, Unsubscribe = true, Cleaned = true }, 1676 | ListId = listId, 1677 | Source = new Mailchimp.Source { Admin = true, User = true }, 1678 | Url = webhookUrl 1679 | }) ?? throw new NopException("No response from the service"); 1680 | } 1681 | 1682 | return true; 1683 | }); 1684 | } 1685 | 1686 | /// 1687 | /// Delete webhooks 1688 | /// 1689 | /// The asynchronous task whose result determines whether webhooks successfully deleted 1690 | public async Task DeleteWebhooksAsync() 1691 | { 1692 | return await HandleRequestAsync(async () => 1693 | { 1694 | //get all account webhooks 1695 | var listNumber = (await _mailChimpManager.Lists.GetResponseAsync())?.TotalItems 1696 | ?? throw new NopException("No response from the service"); 1697 | 1698 | var allListIds = (await _mailChimpManager.Lists.GetAllAsync(new ListRequest { FieldsToInclude = "lists.id", Limit = listNumber })) 1699 | ?.Select(list => list.Id).ToList() 1700 | ?? throw new NopException("No response from the service"); 1701 | 1702 | var allWebhooks = (await Task.WhenAll(allListIds.Select(listId => _mailChimpManager.WebHooks.GetAllAsync(listId)))) 1703 | .SelectMany(webhook => webhook).ToList(); 1704 | 1705 | //generate webhook URL 1706 | var webhookUrl = _urlHelperFactory.GetUrlHelper(_actionContextAccessor.ActionContext) 1707 | .RouteUrl(MailChimpDefaults.WebhookRoute, null, _actionContextAccessor.ActionContext.HttpContext.Request.Scheme); 1708 | 1709 | //delete all webhook with matched URL 1710 | var webhooksToDelete = allWebhooks.Where(webhook => webhook.Url.Equals(webhookUrl, StringComparison.InvariantCultureIgnoreCase)); 1711 | foreach (var webhook in webhooksToDelete) 1712 | { 1713 | await HandleRequestAsync(async () => 1714 | { 1715 | await _mailChimpManager.WebHooks.DeleteAsync(webhook.ListId, webhook.Id); 1716 | return true; 1717 | }); 1718 | } 1719 | 1720 | return true; 1721 | }); 1722 | } 1723 | 1724 | /// 1725 | /// Delete batch webhook 1726 | /// 1727 | /// The asynchronous task whose result determines whether the webhook successfully deleted 1728 | public async Task DeleteBatchWebhookAsync() 1729 | { 1730 | return await HandleRequestAsync(async () => 1731 | { 1732 | //get all batch webhooks 1733 | var allBatchWebhooks = await _mailChimpManager.BatchWebHooks.GetAllAsync(new QueryableBaseRequest { Limit = int.MaxValue }) 1734 | ?? throw new NopException("No response from the service"); 1735 | 1736 | //generate webhook URL 1737 | var webhookUrl = _urlHelperFactory.GetUrlHelper(_actionContextAccessor.ActionContext) 1738 | .RouteUrl(MailChimpDefaults.BatchWebhookRoute, null, _actionContextAccessor.ActionContext.HttpContext.Request.Scheme); 1739 | 1740 | //delete webhook if exists 1741 | var batchWebhook = allBatchWebhooks 1742 | .FirstOrDefault(webhook => webhook.Url.Equals(webhookUrl, StringComparison.InvariantCultureIgnoreCase)); 1743 | 1744 | if (!string.IsNullOrEmpty(batchWebhook?.Id)) 1745 | await _mailChimpManager.BatchWebHooks.DeleteAsync(batchWebhook.Id); 1746 | 1747 | return true; 1748 | }); 1749 | } 1750 | 1751 | /// 1752 | /// Handle batch webhook 1753 | /// 1754 | /// Request form parameters 1755 | /// Already handled batches info 1756 | /// The asynchronous task whose result contains batch identifier and number of completed operations 1757 | public async Task<(string Id, int? CompletedOperationNumber)> HandleBatchWebhookAsync(IFormCollection form, IDictionary handledBatchesInfo) 1758 | { 1759 | return await HandleRequestAsync<(string, int?)>(async () => 1760 | { 1761 | var batchWebhookType = "batch_operation_completed"; 1762 | if (!form.TryGetValue("type", out var webhookType) || !webhookType.Equals(batchWebhookType)) 1763 | return (null, null); 1764 | 1765 | var completeStatus = "finished"; 1766 | if (!form.TryGetValue("data[status]", out var batchStatus) || !batchStatus.Equals(completeStatus)) 1767 | return (null, null); 1768 | 1769 | if (!form.TryGetValue("data[id]", out var batchId)) 1770 | return (null, null); 1771 | 1772 | //ensure that this batch is not yet handled 1773 | var alreadyHandledBatchInfo = handledBatchesInfo.FirstOrDefault(batchInfo => batchInfo.Key.Equals(batchId)); 1774 | if (!alreadyHandledBatchInfo.Equals(default(KeyValuePair))) 1775 | return (alreadyHandledBatchInfo.Key, alreadyHandledBatchInfo.Value); 1776 | 1777 | //log and return results 1778 | var completedOperationNumber = await LogSynchronizationResultAsync(batchId); 1779 | 1780 | return (batchId, completedOperationNumber); 1781 | }); 1782 | } 1783 | 1784 | /// 1785 | /// Handle webhook 1786 | /// 1787 | /// Request form parameters 1788 | /// The asynchronous task whose result determines whether the webhook successfully handled 1789 | public async Task HandleWebhookAsync(IFormCollection form) 1790 | { 1791 | return await HandleRequestAsync(async () => 1792 | { 1793 | //try to get subscriber list identifier 1794 | if (!form.TryGetValue("data[list_id]", out var listId)) 1795 | return false; 1796 | 1797 | //get stores that tied to a specific MailChimp list 1798 | var settingsName = $"{nameof(MailChimpSettings)}.{nameof(MailChimpSettings.ListId)}"; 1799 | var storeIds = await (await _storeService.GetAllStoresAsync()) 1800 | .WhereAwait(async store => listId.Equals(await _settingService.GetSettingByKeyAsync(settingsName, storeId: store.Id, loadSharedValueIfNotFound: true))) 1801 | .Select(store => store.Id).ToListAsync(); 1802 | 1803 | if (!form.TryGetValue("data[email]", out var email)) 1804 | return false; 1805 | 1806 | if (!form.TryGetValue("type", out var webhookType)) 1807 | return false; 1808 | 1809 | //deactivate subscriptions 1810 | var unsubscribeType = "unsubscribe"; 1811 | var cleanedType = "cleaned"; 1812 | if (webhookType.Equals(unsubscribeType) || webhookType.Equals(cleanedType)) 1813 | { 1814 | //get existing subscriptions by email 1815 | var subscriptions = await storeIds 1816 | .SelectAwait(async storeId => await _newsLetterSubscriptionService.GetNewsLetterSubscriptionByEmailAndStoreIdAsync(email, storeId)) 1817 | .Where(subscription => !string.IsNullOrEmpty(subscription?.Email)).ToListAsync(); 1818 | 1819 | foreach (var subscription in subscriptions) 1820 | { 1821 | //deactivate 1822 | subscription.Active = false; 1823 | await _newsLetterSubscriptionService.UpdateNewsLetterSubscriptionAsync(subscription, false); 1824 | await _logger.InformationAsync($"MailChimp info. Email {subscription.Email} was unsubscribed from the store #{subscription.StoreId}"); 1825 | } 1826 | } 1827 | 1828 | //activate subscriptions 1829 | var subscribeType = "subscribe"; 1830 | if (webhookType.Equals(subscribeType)) 1831 | { 1832 | foreach (var storeId in storeIds) 1833 | { 1834 | var subscription = await _newsLetterSubscriptionService.GetNewsLetterSubscriptionByEmailAndStoreIdAsync(email, storeId); 1835 | 1836 | //if subscription doesn't exist, create the new one 1837 | if (subscription == null) 1838 | { 1839 | subscription = new NewsLetterSubscription 1840 | { 1841 | NewsLetterSubscriptionGuid = Guid.NewGuid(), 1842 | Email = email, 1843 | StoreId = storeId, 1844 | Active = true, 1845 | CreatedOnUtc = DateTime.UtcNow 1846 | }; 1847 | await _newsLetterSubscriptionService.InsertNewsLetterSubscriptionAsync(subscription, false); 1848 | } 1849 | else 1850 | { 1851 | //or just activate the existing one 1852 | subscription.Active = true; 1853 | await _newsLetterSubscriptionService.UpdateNewsLetterSubscriptionAsync(subscription, false); 1854 | 1855 | } 1856 | await _logger.InformationAsync($"MailChimp info. Email {subscription.Email} has been subscribed to the store #{subscription.StoreId}"); 1857 | } 1858 | } 1859 | 1860 | return await Task.FromResult(true); 1861 | }); 1862 | } 1863 | 1864 | #endregion 1865 | } -------------------------------------------------------------------------------- /Nop.Plugin.Misc.MailChimp/Services/SynchronizationRecordService.cs: -------------------------------------------------------------------------------- 1 | using Nop.Data; 2 | using Nop.Plugin.Misc.MailChimp.Domain; 3 | 4 | namespace Nop.Plugin.Misc.MailChimp.Services; 5 | 6 | /// 7 | /// Represents MailChimp synchronization record service implementation 8 | /// 9 | public class SynchronizationRecordService : ISynchronizationRecordService 10 | { 11 | #region Fields 12 | 13 | private readonly IRepository _synchronizationRecordRepository; 14 | 15 | #endregion 16 | 17 | #region Ctor 18 | 19 | public SynchronizationRecordService(IRepository synchronizationRecordRepository) 20 | { 21 | _synchronizationRecordRepository = synchronizationRecordRepository; 22 | } 23 | 24 | #endregion 25 | 26 | #region Methods 27 | 28 | /// 29 | /// Get all synchronization records 30 | /// 31 | /// List of synchronization records 32 | public virtual IList GetAllRecords() 33 | { 34 | return _synchronizationRecordRepository.Table.OrderBy(record => record.Id).ToList(); 35 | } 36 | 37 | /// 38 | /// Get a synchronization record by identifier 39 | /// 40 | /// Synchronization record identifier 41 | /// Synchronization record 42 | public virtual async Task GetRecordByIdAsync(int recordId) 43 | { 44 | return recordId == 0 ? null : await _synchronizationRecordRepository.GetByIdAsync(recordId); 45 | } 46 | 47 | /// 48 | /// Get synchronization records by entity type and operation type 49 | /// 50 | /// Entity type 51 | /// Operation type 52 | /// List of aynchronization records 53 | public virtual IList GetRecordsByEntityTypeAndOperationType(EntityType entityType, OperationType operationType) 54 | { 55 | return _synchronizationRecordRepository.Table.Where(record => 56 | record.EntityTypeId == (int)entityType && record.OperationTypeId == (int)operationType).ToList(); 57 | } 58 | 59 | /// 60 | /// Create the new one or update an existing synchronization record 61 | /// 62 | /// Entity type 63 | /// Entity identifier 64 | /// Operation type 65 | /// Email (only for subscriptions) 66 | /// Product identifier (for product attributes, attribute values and attribute combinations) 67 | public virtual async Task CreateOrUpdateRecordAsync(EntityType entityType, int entityId, OperationType operationType, string email = null, int productId = 0) 68 | { 69 | //whether the synchronization record with passed parameters already exists 70 | var existingRecord = _synchronizationRecordRepository.Table 71 | .FirstOrDefault(record => record.EntityTypeId == (int)entityType && record.EntityId == entityId); 72 | if (existingRecord == null) 73 | { 74 | //create the new one if not exists 75 | await InsertRecordAsync(new MailChimpSynchronizationRecord 76 | { 77 | EntityType = entityType, 78 | EntityId = entityId, 79 | OperationType = operationType, 80 | Email = email, 81 | ProductId = productId 82 | }); 83 | return; 84 | } 85 | 86 | //or update the existing 87 | switch (existingRecord.OperationType) 88 | { 89 | case OperationType.Create: 90 | if (operationType == OperationType.Delete) 91 | await DeleteRecordAsync(existingRecord); 92 | return; 93 | 94 | case OperationType.Update: 95 | if (operationType == OperationType.Delete) 96 | { 97 | existingRecord.OperationType = OperationType.Delete; 98 | await UpdateRecordAsync(existingRecord); 99 | } 100 | return; 101 | 102 | case OperationType.Delete: 103 | if (operationType == OperationType.Create) 104 | { 105 | existingRecord.OperationType = OperationType.Update; 106 | await UpdateRecordAsync(existingRecord); 107 | } 108 | return; 109 | } 110 | } 111 | 112 | /// 113 | /// Insert a synchronization record 114 | /// 115 | /// Synchronization record 116 | public virtual async Task InsertRecordAsync(MailChimpSynchronizationRecord record) 117 | { 118 | ArgumentNullException.ThrowIfNull(record); 119 | 120 | await _synchronizationRecordRepository.InsertAsync(record); 121 | } 122 | 123 | /// 124 | /// Update the synchronization record 125 | /// 126 | /// Synchronization record 127 | public virtual async Task UpdateRecordAsync(MailChimpSynchronizationRecord record) 128 | { 129 | ArgumentNullException.ThrowIfNull(record); 130 | 131 | await _synchronizationRecordRepository.UpdateAsync(record); 132 | } 133 | 134 | /// 135 | /// Delete a synchronization record 136 | /// 137 | /// Synchronization record 138 | public virtual async Task DeleteRecordAsync(MailChimpSynchronizationRecord record) 139 | { 140 | ArgumentNullException.ThrowIfNull(record); 141 | 142 | await _synchronizationRecordRepository.DeleteAsync(record); 143 | } 144 | 145 | /// 146 | /// Delete synchronization records by entity type 147 | /// 148 | /// Entity type 149 | public virtual async Task DeleteRecordsByEntityTypeAsync(EntityType entityType) 150 | { 151 | var records = GetAllRecords().Where(record => record.EntityType == entityType); 152 | await _synchronizationRecordRepository.DeleteAsync(records.ToList()); 153 | } 154 | 155 | /// 156 | /// Delete all synchronization records 157 | /// 158 | public virtual async Task ClearRecordsAsync() 159 | { 160 | await _synchronizationRecordRepository.DeleteAsync(GetAllRecords()); 161 | } 162 | 163 | #endregion 164 | } -------------------------------------------------------------------------------- /Nop.Plugin.Misc.MailChimp/Services/SynchronizationTask.cs: -------------------------------------------------------------------------------- 1 | using Nop.Core; 2 | using Nop.Services.Localization; 3 | using Nop.Services.Plugins; 4 | using Nop.Services.ScheduleTasks; 5 | 6 | namespace Nop.Plugin.Misc.MailChimp.Services; 7 | 8 | /// 9 | /// Represents a task that synchronizes data with MailChimp 10 | /// 11 | public class SynchronizationTask : IScheduleTask 12 | { 13 | #region Fields 14 | 15 | private readonly ILocalizationService _localizationService; 16 | private readonly IPluginService _pluginService; 17 | private readonly MailChimpManager _mailChimpManager; 18 | 19 | #endregion 20 | 21 | #region Ctor 22 | 23 | public SynchronizationTask(ILocalizationService localizationService, 24 | IPluginService pluginService, 25 | MailChimpManager mailChimpManager) 26 | { 27 | _localizationService = localizationService; 28 | _pluginService = pluginService; 29 | _mailChimpManager = mailChimpManager; 30 | } 31 | 32 | #endregion 33 | 34 | #region Methods 35 | 36 | /// 37 | /// Execute task 38 | /// 39 | public async Task ExecuteAsync() 40 | { 41 | //ensure that plugin installed 42 | var pluginDescriptor = await _pluginService.GetPluginDescriptorBySystemNameAsync(MailChimpDefaults.SystemName, LoadPluginsMode.InstalledOnly); 43 | if (pluginDescriptor == null) 44 | return; 45 | 46 | //start the synchronization 47 | if (await _mailChimpManager.SynchronizeAsync() == 0) 48 | throw new NopException(await _localizationService.GetResourceAsync("Plugins.Misc.MailChimp.Synchronization.Error")); 49 | } 50 | 51 | #endregion 52 | } -------------------------------------------------------------------------------- /Nop.Plugin.Misc.MailChimp/Views/Configure.cshtml: -------------------------------------------------------------------------------- 1 | @model ConfigurationModel 2 | @{ 3 | Layout = "_ConfigurePlugin"; 4 | } 5 | 6 | @await Component.InvokeAsync(typeof(StoreScopeConfigurationViewComponent)) 7 | 8 | 23 | 24 |
25 |
26 |
27 |
28 |

29 | For plugin configuration follow these steps:
30 |
31 | 1. Sign up for a MailChimp account.
32 | 2. Log in at the MailChimp service.
33 | 3. Go to 'Lists' page. Create a contact list with which newsletter subscribers of your store will be synchronized.
34 | 4. Find 'API Keys' page by going Profile -> Extras -> API keys.
35 | 5. Create a new key and copy it into the form below.
36 | 6. Save.
37 | 7. Choose one of the previously created contact lists.
38 | 8. Check "Pass E-Commerce data" to be able to use MailChimp E-Commerce features. 39 | In this case information about the store, customers, products and orders will be passed to MailChimp. 40 | More information on how to use this data can be found here.
41 | 9. Fill in the remaining fields and save to complete the configuration.
42 |

43 |
44 |
45 | 46 |
47 |
48 | 49 | 50 |
51 |
52 | @if (!string.IsNullOrEmpty(Model.AccountInfo)) 53 | { 54 |
55 |
56 | 57 |
58 |
59 |
@Model.AccountInfo
60 |
61 |
62 | } 63 |
64 |
65 | 66 | 67 |
68 |
69 | 70 | 71 |
72 |
73 |
74 |
75 | 76 |
77 |
78 | 79 | 80 |
81 |
82 | 83 |
84 |
85 | 86 |
87 |
88 | 89 | 90 |
91 |
92 |
93 |
94 |
95 | 96 |
97 |
98 | 99 | 100 |
101 |
102 | 103 |
104 |
105 | 106 |
107 |
108 | 109 | 110 |
111 |
112 |
113 |
114 |
115 | 116 |
117 |
118 |
119 |
120 | 121 | @if (!string.IsNullOrEmpty(Model.ApiKey)) 122 | { 123 |
124 |
125 |
126 | @T("Plugins.Misc.MailChimp.ManualSynchronization.Hint") 127 |
128 | @if (Model.SynchronizationStarted) 129 | { 130 |
131 | 132 |
133 | } 134 |
135 |
136 |

137 | You can synchronize the data of your store with MailChimp manually. 138 | In this case existing data in MailChimp will be deleted first and then passed again completely, unlike auto synchronization when only the updated data is passed. 139 | You can use manual synchronization as the first one or, in case of there are any errors in auto synchronization and you want to reset all data.
140 | Note that it may take a long time.
141 |

142 |
143 | 146 |
147 | 148 | @if (Model.SynchronizationStarted) 149 | { 150 | 151 | 169 | 170 | } 171 | } 172 |
173 |
-------------------------------------------------------------------------------- /Nop.Plugin.Misc.MailChimp/Views/_ViewImports.cshtml: -------------------------------------------------------------------------------- 1 | @inherits Nop.Web.Framework.Mvc.Razor.NopRazorPage 2 | 3 | @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers 4 | @addTagHelper *, Nop.Web.Framework 5 | 6 | @using Microsoft.AspNetCore.Mvc.ViewFeatures 7 | @using Nop.Plugin.Misc.MailChimp.Models 8 | @using Nop.Web.Areas.Admin.Components 9 | @using Nop.Web.Framework.UI 10 | @using Nop.Web.Framework.Extensions 11 | @using System.Text.Encodings.Web -------------------------------------------------------------------------------- /Nop.Plugin.Misc.MailChimp/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nopSolutions/mailchimp-plugin-for-nopcommerce/5fb85133e964a9e88d7423547041753354c30486/Nop.Plugin.Misc.MailChimp/logo.png -------------------------------------------------------------------------------- /Nop.Plugin.Misc.MailChimp/plugin.json: -------------------------------------------------------------------------------- 1 | { 2 | "Group": "Misc", 3 | "FriendlyName": "MailChimp", 4 | "SystemName": "Misc.MailChimp", 5 | "Version": "4.80.1", 6 | "SupportedVersions": [ "4.80" ], 7 | "Author": "nopCommerce team", 8 | "DisplayOrder": 1, 9 | "FileName": "Nop.Plugin.Misc.MailChimp.dll", 10 | "Description": "This plugin allows to integrate with MailChimp service" 11 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # nopCommerce MailChimp plugin 2 | 3 | =========== 4 | 5 | nopCommerce site: [https://www.nopcommerce.com](https://www.nopcommerce.com) 6 | 7 | Listing on nopCommerce "extensions and themes" catalog: [https://www.nopcommerce.com/mailchimp-synchronization-plugin](https://www.nopcommerce.com/mailchimp-synchronization-plugin) 8 | 9 | MailChimp site: [http://www.mailchimp.com/](http://www.mailchimp.com/) 10 | 11 | E-commerce stores: [http://developer.mailchimp.com/documentation/mailchimp/reference/ecommerce/stores/](http://developer.mailchimp.com/documentation/mailchimp/reference/ecommerce/stores/) 12 | 13 | Connect Your Store: [http://mailchimp.com/connect-your-store/](http://mailchimp.com/connect-your-store/) 14 | 15 | =========== 16 | 17 | ## Description 18 | 19 | MailChimp has been around since 2001. The company started as a side project funded by various web-development jobs and now it is one of the world’s leading email marketing platform, which sends more than a billion emails a day. MailChimp’s team of 500+ is growing quickly to support thousands of new customers every day. 20 | 21 | Bring your audience data, marketing channels, and insights together so you can reach your goals faster. With Mailchimp, you can promote your business across email, social, landing pages, postcards, and more — all from a single platform. 22 | 23 | ## Features 24 | 25 | - **Connect the store** 26 | 27 | When connecting the store with one of MailChimp’s hundreds of e-commerce integrations, you can create targeted campaigns, automate helpful product follow-ups, and send back-in-stock messaging. 28 | - **Flexible design** 29 | 30 | Use drag and drop designer to create campaigns or build your own email. MailChimp's collaboration options, like multi-user accounts and comments inside the editor, will speed up the design process. 31 | - **Advanced analytics** 32 | 33 | MailChimp offers advanced reporting features. Monitor sales and website activity with revenue reports, and inform email content with purchase data using Google Analytics. 34 | 35 | ## Installation instructions 36 | 37 | 1. Download the plugin archive. 38 | 1. Go to admin area > configuration > local plugins. 39 | 1. Upload the plugin archive using the "Upload plugin or theme" plugin. 40 | 1. Scroll down through the list of plugins to find the newly installed plugin. And click on the "Install" button to install the plugin. 41 | 1. Register with the MailChimp with [this link](http://eepurl.com/bze81f) 42 | 43 | Please find more information about how to install plugins [here](https://docs.nopcommerce.com/user-guide/configuring/system/plugins.html). 44 | --------------------------------------------------------------------------------