magento table "sales_flat_order" field "protect_code" explanation - mysql

We are working on magento database and tables. Magento seems to write a code in table sales_flat_order field protect_code to define if there is a invoice or a shipment done already. It would look something like
01b335 or
a0a243
But there is no key to understand what this protection code means. Is there an explanation of the meaning of these codes and how they are generated?

Where is it generated?
If you look in app/code/core/Mage/Sales/Model/Order.php on around line 2052, you will find the following:
$this->setData('protect_code', substr(md5(uniqid(mt_rand(), true) . ':' . microtime(true)), 5, 6));
This is where protect_code is generated for the order (using a combination of md5, uniqid, and random integer.
What is it used for?
If you look in app/code/core/Mage/Sales/Helper/Guest.php and find the loadValidOrder function. You will see protect_code used in some areas to ensure the order being loaded is the correct one for the guest's cookie value.
It's also used in other areas, such as tracking information comparisons. You can see several instances of the getProtectCode() method being called in the Shipment models to compare the order to the tracking information. An example of a function that uses it is:
public function getTrackingInfoByTrackId()
{
$track = Mage::getModel('sales/order_shipment_track')->load($this->getTrackId());
if ($track->getId() && $this->getProtectCode() == $track->getProtectCode()) {
$this->_trackingInfo = array(array($track->getNumberDetail()));
}
return $this->_trackingInfo;
}
As you can see with $this->getProtectCode() == $track->getProtectCode(), the tracking protect_code must match the Shipment protect_code.

Related

Laravel Eloquent - auto-numbering on has many relationship

I'm very much a beginner when it comes to database relationships hence what I suspect is a basic question! I have two database tables as follows:
Projects
id
company_id
name
etc...
rfis
id
project_id (foreign key is id on the Projects table above)
Number (this is the column I need help with - more below)
question
The relationships at the Model level for these tables are as follows:
Project
public function rfi()
{
return $this->hasMany('App\Rfi');
}
RFI
public function project()
{
return $this->belongsTo('App\Project');
}
What I'm trying to achieve
In the RFI table I need a system generated number or essentially a count of RFI's. Where I'm finding the difficulty is that I need the RFI number/count to start again for each project. To clarify, please see the RFI table below which I have manually created with the the 'number' how I would like it displayed (notice it resets for each new project and the count starts from there).
Any assistance would be much appreciated!
Todd
So the number field depends on the number of project_id in the RFI table. It is exactly the number of rows with project_id plus one.
So when you want to insert a new row, you calculate number based on project_id and assign it.
RFI::create([
'project_id' => $project_id,
'number' => RFI::where('project_id', $project_id)->count() + 1,
...
]);
What I understood is that you want to set the value of the "number" field to "1" if it's a new project and "increment" if it's an existing project. And you want to automate this without checking for it every time you save a new row for "RFI" table.
What you need is a mutator. It's basically a method that you will write inside the desired Model class and there you will write your own logic for saving data. Laravel will run that function automatically every time you save something. Here you will learn more about mutators.
Use this method inside the "RFI" model class.
public function setNumberAttribute($value)
{
if(this is new project)
$this->attributes['number'] = 1;
else
$this->attributes['number']++;
}
Bonus topic: while talking about mutators, there's also another type of method called accessor. It does the same thing as mutators do, but just the opposite. Mutators get called while saving data, accessors get called while fetching data.

Yii2-How to insert status column and its automatic variations if the corresponding value used by another form

although I have searched in various resources I cannot understand how to correctly insert the ‘status’ column, I will explain better.
I have two sql tables:
From the gestionepc form using dropdown, I can select the numerazionecolumn of thenumerazionitable and so far everything works without problems. However, I need to insert the “status” column on thenumerazionitable so that if I use a record in thenumerazionicolumn, itsstatus` must automatically change to “Not active” as it is already used. For my project, it is a requirement derived from the fact that I have various groups of user permissions and various authorizations.
In practice, I'm very confused about how to insert the status column (type of column, default value, storage also on the MySQL database and initialize it) and on how to make it work through the code (perhaps using afterSave and beforeUpdate).
I read Active Record from Guide Yii2 but I don’t understand.
I modify table numerazioni in this mode:
And I try this in model Numerazioni
const STATUS_INDISPONIBILE = 'Indisponibile';
const STATUS_DISPONIBILE = 'Disponibile';
public function setStatusnumerazione()
{
if (\app\models\Gestionepc::find()->where(!isEmpty('numerazioni_id'))) {
$this->statusnumerazione = self::STATUS_INDISPONIBILE;
}
else {
$this->statusnumerazione = self::STATUS_DISPONIBILE;
}
}
But not working. Thanks in advance.

I can't get an e-mail of a specific contact

Here is my story:
I'm writting a script that permits to see every users in an array of group (I mean, you select 2 group, it show every users in one of these two groups). It also do some other treatment. But it's OK for this part.
Everything seems to work correcly. Except for only one user.
The idea is, I have to get the e-mail of a user, to then compare users'e-mail got in a former group, to see if this user is (or not) already listed ( in order to avoid duplicate).
The user (this one only) won't use my function. I supposed it was a group, but it really is a user.. I'm pretty sure it is an option to select ( or not) in the user's preference, but which one?
PS: here is the error quote
TypeError: Fonction getEmail introuvable dans l'objet
(TypeError: getEmail function not found in object)
And here is the code I use in order to get e-mails:
for(var i in objuser){
for(var j in objuser[i])
{
objuser[i][j]=objuser[i][j].getEmail();
}
}
Objuser is a list of User Object. First dimension (I) is the group, second dimension (j), is users of the "I" group.
PROBLEM NOT SOLVED:
the reason:
I have 2 functions that do treatments. Theses Two function need an array, that another function create (which is long to execute). My code is done in such a way, if i execute consecutively these 2 treatment functions with the same array, the second to be played use an incorrect array.
So i clone it with :
var groupsUser2 = JSON.parse(JSON.stringify(groupsUser));
but, now that i dont use anymore email adresses ( i mean String), but direct Users (i mean Object), the former code don't clone correctly:
array1 : user's array (Objects)
array2 = JSON.parse(JSON.stringify(array1))
log(array1) :[blabla1#...com,blabla2#...com,blabla3#...com, .....]
log(array2) :[{},{},{}………]
SO.... Here is the new question: Is there a simple way to copy an Object's array ?
Here is the former question: What rights configuration unallow me to use the getEmail() function for a specific contact?
I need an answer just for one of these two questions, and i'll be able to correct my problem. Any idea guys???????
never use "for x in array" its bad use of javascript on an array because the array has the "length" property which is a number and not the object your loop expects.
instead use " for (i=0;...." or forEach.
Well, I was using getEmail() function in order to compare users got in one group, to others got in another group , so that i can avoid duplicates.
I was checking with IndexOf() if the user adress were in the array of the other group's users.
I don't know why , but now it works even if i don't get the e-mail of the user. So , the problem that was happening for one user can't happen anymore.
Conclusion: Problem solved. Thx mates
I thought about a solution: try .. catch, so that the email which won't be get, will be potentially duplicated because I will not be able to find the user if already displayed or not without his e-mail, but at least the script will not crash.

difference between key value in adressline and getId() value in Google Script

I wanted to ask what's the difference between the value in the adressline and the id I get when i use getId().
For example for one document the getId() value is:
t8K_TLQPmKzgB72pY4TblUg
while in the adressline the key is:
0Amu7sNvd2IoudDhLX1RMUVBtS3pnQjcycFk0VGJsVWc
what i figured out so far is that when you encode getId in base64 you get more or less the last part of the key in the adressline
(base64Encode(t8K_TLQPmKzgB72pY4TblUg) = dDhLX1RMUVBtS3pnQjcycFk0VGJsVWc=).
But I still don't know what 0Amu7sNvd2Iou stands for, because i have the impression that this parts also is different in older documents, therefore i can't just combine the key using all the time 0Amu7sNvd2Iou at the beginning
Why I need to know this: my scripts use the getId method but some users fill in their ids manually (they just copypaste it from the key from the adressline). The result is that when i try to compare them although they refer to the same document i can't match them like they are completly different...
thanks a lot for bringing light into this problem
edit #taras:
i can also open the document with the key and the id. It's just weird that there are kind of two different id's for one document. If for example i want to compare if a value somebody copypasted from the adressline to a document is the same as the file i have opened i won't get a true, even it is the same file
var keyFromHeadline = "0Amu7sNvd2IoudDhLX1RMUVBtS3pnQjcycFk0VGJsVWc"
var id = SpreadsheetApp.getActiveSpreadsheet.getId();
if (keyFromHeadline==id) Browser.msgBox("blabla")
Therefore i would be interested what is the reason for the two different values and how i could match them
If you need to have unique file IDs just normalize them. Everytime a user enters an ID manually just run it trough the fileIdNormalize function:
function fileIdNormalize(id) {
if (typeof id == 'string' && id.length > 0)
return DocsList.getFileById(id).getId();
return '';
}
Just a suggestion :
Since base64Encode seems to give you a significative part of the adress url you could use a match to check if the document is the same.
Something like :
if('manually_entered_key'.match(base64Encode('the_value_obtained_by_getId')==base64Encode('the_value_obtained_by_getId')){
// consider as the same doc ...

"Diffing" objects from a relational database

Our win32 application assembles objects from the data in a number of tables in a MySQL relational database. Of such an object, multiple revisions are stored in the database.
When storing multiple revisions of something, sooner or later you'll ask yourself the question if you can visualize the differences between two revisions :) So my question is: what would be a good way to "diff" two such database objects?
Would you do the comparison at the database level? (Doesn't sound like a good idea: too low-level, and too sensitive to the schema).
Would you compare the objects?
Would you write a function that "manually" compares the properties and fields of two objects?
How would you store the diff? In a separate, generic "TDiff" object?
Any general recommendations on how to visualize such things in a user interface?
Advice, or stories about your own experiences with this, are very welcome; thanks a bunch!
Extra info on use case (20090515)
In reply to Antony's comment: this specific application is used to schedule training courses, run by teams of teachers. The schedule of a teacher is stored in various tables in the database, and contains info such as "where does she have to go on which day", "who are her colleagues in the team", etc. This information is spread out over multiple tables.
Once in a while, we "publish" the schedule, so the teachers can see it on a webpage. Each "publication" is a revision, and we'd like to be able to show the users (and later also the teachers) what's changed between two publications --- if anything.
Hope that makes the scenario a bit more tangible :)
Some final remarks
Well, the bounty has come to an end, so I've accepted an answer. If it'd somehow be possible to slice a couple of extra 100's off of my rep and give it to some of the other answers, I would do so without hesitation. All your guys' help has been great, and I am very grateful! ~ Onno 20090519
Just an idea, but would it be worthwhile for you to convert the two object versions being compared to some text format and then comparing these text objects using an existing diff program - like diff for example? There are lots of nice diff programs out there that can offer nice visual representations, etc.
So for example
Text version of Object 1:
first_name: Harry
last_name: Lime
address: Wien
version: 0.1
Text version of Object 2:
first_name: Harry
last_name: Lime
address: Vienna
version: 0.2
The diff would be something like:
3,4c3,4
< address: Wien
< version: 0.1
---
> address: Vienna
> version: 0.2
Assume that a class has 5 known properties - date, time, subject, outline, location. When I look at my schedule, I'm most interested in the most recent (ie current/accurate) version of these properties. It would also be useful for me to know what, if anything, has changed. (As a side note, if the date, time or location changed, I'd also expect to get an email/sms advising me in case I don't check for an updated schedule :-))
I would suggest that the 'diff' is performed at the time the schedule is amended. So, when version 2 of the class is created, record which values have changed, and store this in two 'changelog' fields on the version 2 object (there must already be one parent table that sits atop all your tables - use that one!). One changelog field is 'human readable text' eg 'Date changed from Mon 1 May to Tues 2 May, Time changed from 10:00am to 10:30am'. The second changelog field is a delimted list of changed fields eg 'date,time' To do this, before saving you would loop over the values submitted by the user, compare to current database values, and concatenate 2 strings, one human readable, one a list of field names. Then, update the data and set your concatenated strings as the 'changelog' values.
When displaying the schedule load the current version by default. Loop through the fields in the changelog field list, and annotate the display to show that the value has changed (a * or a highlight, etc). Then, in a separate panel display the human readable change log.
If a schedule is amended more than once, you would probably want to combine the changelogs between version 1 & 2, and 2 & 3. Say in version 3 only the course outline changed - if that was the only changelog you had when displaying the schedule, the change to date and time wouldn't be displayed.
Note that this denormalised approach won't be great for analysis - eg working out which specific location always has classes changed out of it - but you could extend it using an E-A-V model to store the change log.
Doing a comparison at the database level would be good if what you cared about was changes to the database. That makes the most sense if you're trying to design a layer of generic functionality on top of the database itself.
Doing a comparison at the object level would be good if you care about changes to the data. For example, if the data was the input to a program and you were interested in looking at changes in the input to verify that changes to the output were correct.
Your use case doesn't appear to be either of these. You appear to care about the output and want differences from that perspective. If that's the case, I would do differences on the output report (or a pure-text version of it) instead of on the underlying data. You can do that with any off-the-shelf diff tool. To make things easier for your end-users you could parse the diff results and render them as HTML. There are lots of options here: side-by-side with color coding to indicate changes, one document with markup for changes (e.g. red strikethrough for deletions and green for additions), maybe just highlight areas that have changed and use balloons to show the previous/current values on demand.
I've thought about doing database comparisons but never tried to implement it. As you noted, any such attempts are intimately intertwined with the schema.
I have done object-level comparisons. The general algorithm was this:
Do a set comparison on the lists of object IDs. This creates three result groupings: added objects, deleted objects, and objects that live in both sets.
Report the deletions.
Report the additions.
For the things in both sets, do an attribute-by-attribute comparison.
If any differences are found, report the object ID, the attributes that differ, and the respective values. If appropriate, highlight the portion of the attribute value that has changed.
In my case, the comparison algorithms were hand-written to match the object attributes. This gave me control over which attributes were compared and how. A generic comparator might be possible for some cases but would depend on the situation and at least partially on the implementation language.
I've looked into MysQL Diffing a number of times. Unfortunately, there aren't any really good solutions available.
One tool I've tried was mysqldiff (www.mysqldiff.org). mysqldiff is a tool written in PHP which is capable of diffing mysql schemas. Unfortunately, it doesn't do a great job a lot of the time.
MySQL Workbench, MySQLs own SQL IDE provides the option to generate an alter script and I would imagine it does this by performing some kind of diff operation internally.
Aqua Data Studio is another tool that is capable of comparing schemas and outputing a diff of the two. While the ADS diff is quite nice, it does not provide a tool to create an alter script.
If I were writing my own I guess I would write code capable of comparing structure of two tables. Such code could be tuned to be highly sensitive (Ig if column order differs from from version to the next, it's a difference) or more moderately sensitive (Eg Column order is not a major issue, datatypes and lengths are important, as are indices and constraints).
Storage, I'm not to sure. I would look into how a version control system such as Mercurial stores its diff information for revisions and use that to elaborate a method appropriate for the DB.
Finally, for visual output I recommend you take a look at the Aqua Data Stduio compare feature (You can use the Trial version to test this...). Its diff output is pretty good.
My application dbscript compares hierarchical data (database schemas) in a stored procedure, which of course has to compare each field/property of every object with its counterpart. I guess you won't get around that step (unless you have a generic object description model)
As for the UI part of your question, have a look at screenshots to view and select differences.
I would think about some sort of common text representation of the objects and let the texts compare with an existing diffing tool like WinMerge.
I see no need to invent diffing by myself since there are already plenty of nice tools I can use.
In your situation in PostgreSQL I used a difference tables with the schema:
history_columns (
column_id smallint primary key,
column_name text not null,
table_name text not null,
unique (table_name, column_name)
);
create temporary sequence column_id_seq;
insert into history_columns
select nextval('column_id_seq'), column_name, table_name
from information_schema.columns
where
table_name in ('table1','table2','table3')
and table_schema=current_schema() and table_catalog=current_database();
create table history (
column_id smallint not null references history_columns,
id int not null,
change_time timestamp with time zone not null
constraint change_time_full_second -- only one change allowed per second
check (date_trunc('second',change_time)=change_time),
primary key (column_id,id,change_time),
value text
);
And on the tables I used a trigger like this:
create or replace function save_history() returns trigger as
$$
if (tg_op = 'DELETE') then
insert into historia values (
find_column_id('id',tg_relname), OLD.id,
date_trunc('second',current_timestamp),
OLD.id );
[for each column_name] {
if (char_length(OLD.column_name)>0) then
insert into history values (
find_column_id(column_name,tg_relname), OLD.id,
OLD.change_time, OLD.column_name
)
}
elsif (tg_op = 'UPDATE') then
[for each column_name] {
if (OLD.column_name is distinct from NEW.column_name) then
insert into history values (
find_column_id(column_name,tg_relname), OLD.id,
OLD.change_time, OLD.column_name
);
end if;
}
end if;
$$ language plpgsql volatile;
create trigger save_history_table1
before update or delete on table1
for each row execute procedure save_history();
This isn't really an answer to the question you asked rather an attempt to re-imagine the problem. Would you consider altering your database and object model to store the aggregate root and a series of deltas? That is, model and store RevisionSets that are collections of Revisions; a Revision is an entity property paired with a value. In a sense this is internalizing the revision structure into your architecture that the other posters are suggesting that you bolt-on to what you already have via "logs".
It's trivial to display the aggregate from the deltas, and even easier to display the deltas as a change history. The fact that you are using a rich client with state and local memory makes this even more compelling. You could very easily display "all the changes since date xxxx" without revisiting the database.
Credit for the basic idea goes to Greg Young and his work with financial data streams, but it is imminently applicable to your problem.
I'm riffing off of what Harry Lime suggested: Output your properties to text format, then hash the results. That way you can compare the hash values and easily flag the data that has been altered. This way you get the best of both worlds as you can visually see differences but programmatically identify differences. With the has you'll have a good source for an index should you want to store and retrieve the deltas.
Given you want to create a UI for this and need to indicate where the differences are, it seems to me you can either go custom or create a generic object comparer - the latter being dependent on the language you are using.
For the custom method, you need to create a class that takes to two instances of the classes to be comparied. It then returns differences;
public class Person
{
public string name;
}
public class PersonComparer
{
public PersonComparer(Person old, Person new)
{
....
}
public bool NameIsDifferent() { return old.Name != new.Name; }
public string NameDifferentText() { return NameIsDifferent() ? "Name changed from " + old.Name + " to " + new.Name : ""; }
}
This way you can use the NameComparer object to create your GUI.
The gereric approach would be much the same, just that you generalize the calls, and use object insepection (getObjectProperty call below) to find differences;
public class ObjectComparer()
{
public ObjectComparer(object old, object new)
{
...
}
public bool PropertyIsDifferent(string propertyName) { return getObjectProperty(old, propertyName) != getObjectProperty(new, propertyName) };
public string PropertyDifferentText(string propertyName) { return PropertyIsDifferent(propertyName) ? propertyName + " " + changed from " + getObjectProperty(old, propertyName) + " to " + getObjectProperty(new, propertyName): ""; }
}
}
I would go for the second, as it makes things really easy to change GUI on needs. The GUI I would try 'yellowing' the differences to make them easy to see - but that depends on how you want to show the differences.
Getting the object to compare would be loading your object with the initial revision and latest revision.
My 2 cents... Not as techy as the database compare stuff already here.
Have you looked at Open Source DiffKit?
www.diffkit.org
I think it does what you want.
Example with Oracle.
Export ordered objects to text with dbms_metadata
Export ordered tables data into CSV or query format
Make big text file
Diff